McRui
McRui

Reputation: 1931

Get table multiple relations

I have the following eloquent call:

\App\Models\AwardRecommendation::with('entities', 'countries')->get();

When I ask for with 'countries' is because the 'entities' table has the country_id and not the 'awards' table.

The models I have are: AwardRecommendation, Entity, ErnySans\Laraworld\Models\Countries

What I'm trying to do is to get the country data in the query but in the return response I just get:

0 => array:27 [▼
"id" => 1
"guid" => "268f1080-67f3-48e5-844d-96b8c09c339b"
"user_id" => null
"title" => "Example Title"
"slug" => "example-title"
"intro" => null
"description" => null
"type" => "award"
"scope" => "firm"
"scope_name" => "1"
"scope_practice_area_id" => 1
"entity_id" => 1
"year" => null
"image_badge" => null
"image_one" => null
"image_two" => null
"notes" => null
"language" => "en"
"state" => 1
"ordering" => 0
"created_by" => null
"updated_by" => null
"deleted_by" => null
"created_at" => null
"updated_at" => null
"entities" => array:1 [▼
  0 => array:45 [▼
    "id" => 1
    "guid" => "b00e2be5-e1bb-4f98-8a35-30f2f7dfceba"
    "award_id" => 1
    "entity_name" => "Example entity"
    "slug" => "example-entity"
    "url" => null
    "description" => null
    "title" => "Mr."
    "first_name" => "John"
    "last_name" => "McNamarca"
    "email" => "[email protected]"
    "department" => null
    "phone" => "+1 (646) 412 123456"
    "mobile_phone" => null
    "home_phone" => null
    "other_phone" => null
    "fax" => null
    "assistant" => null
    "assistant_phone" => null
    "do_not_call" => 0
    "do_not_email" => 0
    "do_not_fax" => 0
    "email_opt_out" => 0
    "fax_opt_out" => 0
    "street" => null
    "city" => null
    "country_state" => null
    "zip" => null
    "country_id" => 240
    "street_other" => null
    "city_other" => null
    "state_other" => null
    "zip_other" => null
    "country_id_other" => 240
    "notes" => null
    "language" => "en"
    "state" => 1
    "ordering" => 0
    "created_by" => null
    "updated_by" => null
    "deleted_by" => null
    "deleted_at" => null
    "created_at" => null
    "updated_at" => null
    "pivot" => array:1 [▼
      "entity_id" => 1
    ]
  ]
]
"countries" => null

How can I get this done with Laravel Eloquent?

Thanks in advance for any help

Upvotes: 1

Views: 37

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

You need to define the relationship in the Entity model first:

public function country()
{
    return $this->belongsTo(ErnySans\Laraworld\Models\Countries::class);
}

And make sure ErnySans\Laraworld\Models\Countries is the correct full class name for Countries model.

Then load award recommendations with related entities and with each entity's country:

AwardRecommendation::with('entities.country')->get();

Upvotes: 2

Related Questions