Laravel Eloquent: multiple foreign keys for relationship

后端 未结 3 724
被撕碎了的回忆
被撕碎了的回忆 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:51

    I had to deal with a similar problem. The solution provided by @fab won't work with eager loading because $this->source_file would be null at the time the relationship is processed. I came up with this solution

    After installing Compoships and configuring it in your models, you can define your relationships matching multiple columns.

    The owning side:

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

    The inverse side:

    use Illuminate\Database\Eloquent\Model;
    use Awobaz\Compoships\Compoships;
    
    class Trip extends Model
    {
        use Compoships;
    
        public function route()
        {
            return $this->belongsTo('Route', ['route_id', 'route_name', 'source_file'], ['id', 'route_name', 'source_file']);
        }
    }
    

    Compoships supports eager loading.

提交回复
热议问题