代码之家  ›  专栏  ›  技术社区  ›  McRui

获取表多个关系

  •  1
  • McRui  · 技术社区  · 7 年前

    我有以下雄辩的呼吁:

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

    当我向' countries '是因为' entities '表具有 country_id 而不是' awards '表。

    我拥有的型号有: AwardRecommendation , Entity , ErnySans\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 回复  |  直到 7 年前
        1
  •  2
  •   Alexey Mezenin    7 年前

    您需要在 Entity 型号优先:

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

    确保 ErnySans\Laraworld\Models\Countries 是的正确完整类名 Countries 模型

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

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