postgresql laravel属于有条件的
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27163716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
laravel belongstomany with condition
提问by Dariel Pratama
i have the following model.
我有以下型号。
class Training extends \Eloquent {
// Add your validation rules here
public static $rules = [
'name' => 'required',
'city' => 'required',
'province' => 'required',
'budget_year' => 'required|integer',
's_date' => 'required|date',
'e_date' => 'required|date'
];
// Don't forget to fill this array
protected $fillable = [
'name',
'city',
'province',
'budget_year',
's_date',
'e_date'
];
public function material(){
return $this->hasMany('Material');
}
public function budget(){
return $this->belongsToMany('Budget')->withPivot('amount');
}
public function budgetById($training_id){
$this->belongsToMany('Budget')->where('training_id', '=', $training_id)->get();
}
}
when i debug the budgetById
method using DB::getQueryLog
, the query is as follow
当我调试budgetById
使用的方法时DB::getQueryLog
,查询如下
select budgets.*,
budget_training.training_id as pivot_training_id,
budget_training.budget_id as pivot_budget_id
from budgets inner join budget_training on budgets.id = budget_training.budget_id
where budget_training.training_id is null and training_id='6'
which return 0 rows, but when i try to modify the query and run it in pgadmin, the following script works well.
它返回 0 行,但是当我尝试修改查询并在 pgadmin 中运行它时,以下脚本运行良好。
select budgets.*,
budget_training.training_id as pivot_training_id,
budget_training.budget_id as pivot_budget_id
from budgets inner join budget_training on budgets.id = budget_training.budget_id
where budget_training.training_id='6'
notice i remove training_id is null and
from laravel generated query. what is wrong with my budgetById
method?
注意我training_id is null and
从 Laravel 生成的查询中删除。我的budgetById
方法有什么问题?
回答by The Alpha
You have called get()
and didn't use return
here:
您已致电get()
但未return
在此处使用:
public function budgetById($training_id){
// = in where is optional in this case
$this->belongsToMany('Budget')->where('training_id', '=', $training_id);
}
You should use like this:
你应该这样使用:
public function budgetById($training_id){
// = in where is optional in this case
return $this->belongsToMany('Budget')->where('training_id', '=', $training_id);
}