我有以下模型。

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

}

当我使用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'

返回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);
}

10-06 06:27