【问题标题】:constrain using two one to many relations in Laravel Eloquent在 Laravel Eloquent 中使用两个一对多关系进行约束
【发布时间】: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)

【问题讨论】:

    标签: laravel eloquent orm


    【解决方案1】:

    像这样更改您的目标模型:

    class Objective extends Model
    {
        
         public function subjects() {
            return $this->belongsTo('App\Models\Subject');
        }
         
        public function yeargroups()
        {
            return $this->belongsTo('App\Models\Yeargroup');
        }
    }
    

    在此处阅读更多信息:https://laravel.com/docs/8.x/eloquent-relationships#one-to-many-inverse

    【讨论】:

    • 这不再是错误,谢谢。但是我并没有得到我需要的回报。我现在需要通过主题 ID 进行约束,而不是看到所有主题的目标。
    • 根据你需要的数据,将with()从:'yeargroups' => Yeargroup::with('objectives.subjects')->get()改为:'yeargroups' => Yeargroup::with('objectives')->get()
    猜你喜欢
    • 2015-03-27
    • 2015-04-26
    • 2016-09-21
    • 2013-02-09
    • 1970-01-01
    • 2020-11-08
    • 2017-04-20
    • 2021-04-21
    • 1970-01-01
    相关资源
    最近更新 更多