得到表多个关系

时间:2018-02-23 11:43:20

标签: laravel laravel-eloquent database-relations

我有以下雄辩的电话:

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

当我要求' countries'因为' entities'表格中包含country_id而不是&{39; awards'表

我拥有的模型是:AwardRecommendationEntityErnySans\Laraworld\Models\Countries

我尝试做的是在查询中获取国家/地区数据,但在返回的回复中我只是得到:

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" => "john.mcnamara@examplecompany.com"
    "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

如何使用Laravel Eloquent完成这项工作?

提前感谢您提供任何帮助

1 个答案:

答案 0 :(得分:2)

您需要先在Entity模型中定义关系:

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

并确保ErnySans\Laraworld\Models\CountriesCountries模型的正确完整类名。

然后向相关实体和每个实体的国家/地区加载奖励建议:

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