簡體   English   中英

"Laravel 嵌套關系"

[英]Laravel nested relationships

我無法讓非常嵌套的關系在 laravel 中正常工作。

想要的行為如下,

我通過 ID 選擇一個事件,我想查看哪些人訂閱了它。<\/strong> 現在的問題是事件和人之間有一些表格..

這是有效的查詢!

SELECT persons.id, 
       persons.firstname, 
       persons.lastname, 
       event_scores.score 
FROM   events 
       JOIN cities 
         ON cities.id = events.city_id 
       JOIN companies 
         ON cities.id = companies.city_id 
       JOIN persons 
         ON companies.id = persons.company_id 
       JOIN event_scores 
         ON event_scores.person_id = persons.id 
WHERE  event_scores.event_id = 1 
GROUP  BY persons.id 
return Event::with('city.companies.persons')->get();

如果您只想從persons表中選擇某些字段,請使用以下命令:

return Event::with(['city.companies.persons' => function ($query) {
    $query->select('id', '...');
}])->get();

對於城市和公司特定的領域,你需要用 eloquent 分發。 例如:

return Event::with([
    'city' => function ($query) {
        $query->select('id', '...');
    },
    'city.companies' => function ($query) {
        $query->select('id', '...');
    },
    'city.companies.persons' => function ($query) {
        $query->select('id', '...');
    }
])->get();

我為這樣的案例創建了一個HasManyThrough關系: GitHub 上的存儲庫

安裝后,您可以像這樣使用它:

class Event extends Model {
    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;

    public function persons() {
        return $this->hasManyDeep(
            Person::class,
            [City::class, Company::class],
            ['id'],
            ['city_id']
        );
    }
}

您可以使用withIntermediate()從中間表中獲取屬性:

public function persons() {
    return $this->hasManyDeep(
        Person::class,
        [City::class, Company::class],
        ['id'],
        ['city_id']
    )->withIntermediate(City::class, ['id', '...']);
}
return Event::with(['city:id,name', 'city.companies:id,name', 'city.companies.persons:id,name'])->get();

擴展@rashmi-nalwaya 的答案。 我通過一些調整讓它在 5.8 項目中工作。

我的例子有點不同,因為我試圖引用 hasOne 關系,而不是 hasMany。

所以作為參考,域名屬於一個網站,屬於一個服務器。 我只想從所有這些表中返回某些列。 我不得不這樣做。

Domain::with([
    'website' => function($q){
        $q->select('id', 'server_id');
    },
    'website.server' => function($q){
        $q->select('id', 'hostname', 'nickname');
    }
])
    ->select('id', 'website_id', 'domain')
    ->get();

必須確保我在任何時候都通過了我所在表的主鍵(所以在我的例子中是id ),其次,我試圖訪問的相關表的外鍵。 所以來自域的website_id和來自網站的server_id 然后它完美地工作。

在我的代碼中,我在主域上還有一個進一步的 where 子句,畢竟這一切都是如此。

這是我的項目代碼,我在這里使用了它。

Checkout::where('cart_number', $cart_number)->with('orders.product')->first();

結果:

 "id": 23,
  "user_id": 4,
  "cart_number": "20219034",
  "phone_number": null,
  "mobile": "01533149024",
  "alternate_phone": "01533149024",
  "country_id": 19,
  "state_id": 750,
  "city_id": 8457,
  "address": "272/1-B, West Nakhalpara,Tejaon,Dhaka",
  "postal_code": "1215",
  "note": "dasd",
  "total": 974,
  "payment_type": "pending",
  "payment_status": 0,
  "courier_id": 3,
  "delivery_status": 0,
  "commented_by": null,
  "rating": null,
  "review": null,
  "coupon_code": null,
  "coupon_status": null,
  "created_at": "2021-10-09T14:59:46.000000Z",
  "updated_at": "2021-10-09T15:33:35.000000Z",
  "orders": [
    {
      "id": 32,
      "user_id": 4,
      "checkout_id": 23,
      "product_id": 2,
      "cart_number": 20219034,
      "courier_id": 3,
      "order_number": "202190340",
      "price": "554",
      "quantity": "1",
      "payment_type": "cod",
      "delivery_status": "pending",
      "created_at": "2021-10-09T14:59:46.000000Z",
      "updated_at": "2021-10-09T14:59:46.000000Z",
      "product": {
        "id": 2,
        "name": "Jasmine Bowers",
        "slug": "jasmine-bowers",
        "media_link": null,
        "description": null,
        "regular_price": 905,
        "sale_price": 554,
        "sku": "32312312",
        "have_stock": 1,
        "stock_quantity": 312,
        "stock_alert_quantity": 50,
        "weight": 5,
        "shipping_class_id": 1,
        "downloadable_file": null,
        "download_limit": null,
        "download_expiry": null,
        "short_description": null,
        "category": "[\"1\"]",
        "brand": 1,
        "tags": "[\"praesentium exceptur\"]",
        "product_image": "http://localhost/Bajaar/media/logo.png",
        "color": "[\"green\"]",
        "size": "[\"fugiat proident del\"]",
        "model": "[\"molestiae quia aute\"]",
        "other": "[\"corrupti enim illo\"]",
        "draft": 1,
        "uploaded_by": 1,
        "created_at": "2021-07-12T20:39:41.000000Z",
        "updated_at": "2021-07-12T20:39:41.000000Z"
      }
    }

事件模型中的兩個級別

public function cities()
{
    return $this->belongsToMany(City::class)->with('companies');
}

為此,許多開發人員會遇到這個問題; 您可以在 whereRelation 子句中鏈接關系以模仿連接,例如

<\/blockquote>


   
這些關系可以繼續用點表示法嵌套。 希望它可以節省你的喧囂。

<\/blockquote>"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM