gpt4 book ai didi

php - laravel belongstomany 有条件

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:00:42 25 4
gpt4 key购买 nike

我有以下模型。

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();
}

}

当我使用DB::getQueryLog调试budgetById方法时,查询如下

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'

它返回 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'

注意我从 Laravel 生成的查询中删除了 training_id is null and。我的 budgetById 方法有什么问题?

最佳答案

你已经调用了 get() 而没有在这里使用 return:

public function budgetById($training_id){
// = in where is optional in this case
$this->belongsToMany('Budget')->where('training_id', '=', $training_id);
}

你应该这样使用:

public function budgetById($training_id){
// = in where is optional in this case
return $this->belongsToMany('Budget')->where('training_id', '=', $training_id);
}

关于php - laravel belongstomany 有条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27163716/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com