用两个一对多关系约束Laravel雄辩
我想约束使用两个一对多关系,使用Laravel雄辩;当添加第二个约束作为方法时,错误表明查询的运行方式与我实际需要的相反,我对Laravel的经验还不够丰富,因此不知道为什么会发生这种情况用两个一对多关系约束Laravel雄辩,laravel,eloquent,orm,Laravel,Eloquent,Orm,我想约束使用两个一对多关系,使用Laravel雄辩;当添加第二个约束作为方法时,错误表明查询的运行方式与我实际需要的相反,我对Laravel的经验还不够丰富,因此不知道为什么会发生这种情况 class YeargroupController extends Controller { public function index($id) { $yeargroups = Yeargroup::get();
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');
}
}
错误
如下更改您的目标模型:
class Objective extends Model
{
public function subjects() {
return $this->belongsTo('App\Models\Subject');
}
public function yeargroups()
{
return $this->belongsTo('App\Models\Yeargroup');
}
}
请在此处阅读更多信息:这不再是错误,谢谢。然而,我并没有得到我所需要的回报。现在我需要通过主题id进行约束,而不是查看所有主题的目标。根据您需要的数据,将
with()
从:'yeargroups'=>yeargroups::with('objectives.subjects')->get()
更改为:'yeargroups'=>yeargroups::with('objectives')->get()
class Objective extends Model
{
public function subjects() {
return $this->belongsTo('App\Models\Subject');
}
public function yeargroups()
{
return $this->belongsTo('App\Models\Yeargroup');
}
}