亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用eloquent在laravel中加入3個表?

如何使用eloquent在laravel中加入3個表?

PHP
RISEBY 2021-06-15 17:14:49
如何使用 laravel 5 中的 eloquent 從 3 表中獲取一些數據?我有 3 個表,列表,卡片,用戶列出模型public function card()    {        return $this->hasMany(Card::class);    }卡片型號public function lists()    {        return $this->belongsTo(Lists::class);    }public function member()    {        return $this->belongsToMany(User::class)->withPivot('status','user_role')->withTimestamps();    }用戶模型public function card_member(){        return $this->belongsToMany(Card::class)->withTimestamps();    }我想在分配給特定用戶的卡片中獲取列表(例如 user_id :2)喜歡這個 JSOn 數據{    "id": 2,    "boards_id": "1",    "list_name": "List 2 B1 U1",    "position": 2,    "created_at": "2019-04-03 16:02:03",    "updated_at": "2019-04-03 16:02:03",    "card": [      {        "id": 8,        "lists_id": "2",        "card_title": "Card 3 L2",        "labels": null,        "description": null,        "start_card": null,        "end_card": null,        "position": 2,        "is_archieved": false,        "created_at": "2019-04-26 15:34:22",        "updated_at": "2019-04-26 15:34:22"      },      {        "id": 9,        "lists_id": "2",        "card_title": "Card 4 L2",        "labels": null,        "description": null,        "start_card": null,        "end_card": null,        "position": 3,        "is_archieved": false,        "created_at": "2019-04-26 15:34:25",        "updated_at": "2019-04-26 15:34:25"      }表結構: 列表:idboards_idlistnameposition卡片 :idlists_idcard_titleCard_user(數據透視表):idcard_iduser_id
查看完整描述

1 回答

?
交互式愛情

TA貢獻1712條經驗 獲得超3個贊

讓我們將關系名稱從“成員”更改為“成員”,因為這是多對多關系。


public function members()

    {

        return $this->belongsToMany(User::class)->withPivot('status','user_role')->withTimestamps();

    }

你可能會說:


$userId = 2;


$lists = List::with([

    'card' => function ($query) {

        $query->whereHas('members', function ($query) user ($userId) {

            $query->whereKey($userId);

        })

    }

])

->whereHas('card.members', function ($query) use ($userId) {

    $query->whereKey($userId);

})

->get();

所以我們只急切加載用戶 ID 為 2 的卡片。


查看完整回答
反對 回復 2021-06-19
  • 1 回答
  • 0 關注
  • 129 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號