Laravel Eloquent: multiple foreign keys for relationship

后端 未结 3 715
被撕碎了的回忆
被撕碎了的回忆 2020-12-06 10:22

I am in the process of porting a project to Laravel.

I have two database tables which are in a One-To-Many relationship with each other. They are joined by three con

3条回答
  •  旧巷少年郎
    2020-12-06 10:36

    As Jonathon already mentioned, you could try to add an where-clause to your relationship:

    use Illuminate\Database\Eloquent\Model;
    
    class Route extends Model
    {
        public function trips()
        {
            return $this->hasMany('Trip', 'route_name')->where('source_file', $this->source_file);
        }
    }
    

    The inverse side:

    use Illuminate\Database\Eloquent\Model;
    
    class Trip extends Model
    {
        public function routes()
        {
            return $this->belongsTo('Route', 'route_name')->where('source_file', $this->source_file);
        }
    }
    

提交回复
热议问题