1

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.

Mukund Bharti
  • 251
  • 4
  • 19

1 Answers1

0

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();
Raphael Cunha
  • 1,084
  • 6
  • 9
  • Thanks for your answer ! I know this way. Response data has object. But I wanted to get directly assigned data to table column name. There is no way ? – happy Coyote Oct 06 '20 at 02:23
  • Can you explain a little more what you’re trying to achieve? You can edit your original question with what you envision the end goal to be. – Raphael Cunha Oct 07 '20 at 04:02