【发布时间】:2020-11-16 21:58:31
【问题描述】:
我想使用 Laravel Eloquent 约束使用两个一对多的关系;当添加第二个约束作为方法时,错误表明查询正在与我实际需要的相反运行,我对 Laravel 的经验还不够,还不知道为什么会发生这种情况。
class YeargroupController extends Controller
{
public function index($id)
{
$yeargroups = Yeargroup::get();
$objectives = Yeargroup::find(1)->objectives->where('subject_id',$id);
return view('admin.yeargroups.index',[
'yeargroups' => Yeargroup::with('objectives.subjects')->get(),
],compact('objectives','yeargroups'));
}
}
模型
class Objective extends Model
{
public function subjects() {
return $this->hasOne('App\Models\Subject');
}
public function yeargroups()
{
return $this->hasOne('App\Models\Yeargroup');
}
}
class Subject extends Model
{
public function objectives() {
return $this->hasMany('App\Models\Objective');
}
}
class Yeargroup extends Model
{
public function objectives()
{
return $this->hasMany('App\Models\Objective');
}
}
错误
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'subjects.objective_id' in 'where clause' (SQL: select * from `subjects` where `subjects`.`objective_id` in (1, 2) and `subjects`.`deleted_at` is null)
【问题讨论】: