Search code examples
laravelmodelone-to-manyrelation

one to many relationship laravel with multiple foreign key


I am on a project with Laravel.

I have two database tables that are in a One-To-Many relationship with each other. They are joined by three conditions. How do I model this relationship in Eloquent?

I am not supposed to modify the database schema, since it has to remain backward compatible with other things.

I have tried the following, but it doesn't work. The owning side:

use Illuminate\Database\Eloquent\Model;

class Route extends Model
{
    public function trips()
    {
        return $this->hasMany('Trip', 'route_name,source_file', 'route_name,source_file')
    }
}

The inverse side:

use Illuminate\Database\Eloquent\Model;

class Trip extends Model
{
    public function routes()
    {
        return $this->belongsTo('Route', 'route_name,source_file', 'route_name,source_file');
    }
}

I don't want to use "use Awobaz\Compoships\Compoships;"


Solution

  • You need to give hasMany() and belongsTo method the namespace of your models. Something like 'App\Models\Trip' or Trip::class

    class Route extends Model
    {
        public function trips()
        {
            return $this->hasMany('App\Models\Trip', 'route_name,source_file', 'route_name,source_file')
        }
    }
    
    class Trip extends Model
    {
        public function routes()
        {
            return $this->belongsTo('App\Models\Route', 'route_name,source_file', 'route_name,source_file');
        }
    }