How to define multiple belongsTo in laravel

1.4k Views Asked by At

My table has many foreign key for example prefecture_id, gender_id and status_id.

And I made model for those table.

So I want to define multiple belongsTo method like following for get all data with query builder..

But In fact belongsTo can't use like this.

public function foreign(){

 return $this->belongsTo([
   'App/Prefecture',
   'App/Gender',                        
   'App/Status',
]
}

And if the only way is defining multiple method for belongs to.

How do I get all belongstos data in querybuilder.

Please give me advice.

1

There are 1 best solutions below

2
On

As far as I am aware, there's not a way to get multiple belongsTo from a single method. What you have to do is make one method for each relationship and when you want to load the relationships you can do the following.

Model

public function prefecture()
{
    return $this->belongsTo(\App\Prefecture::class);
}

public function gender()
{
    return $this->belongsTo(\App\Gender::class);
}

public function status()
{
    return $this->belongsTo(\App\Status::class);
}

Query

// This will get your model with all of the belongs to relationships.

$results = Model::query()->with(['prefecture', 'gender', 'status'])->get();