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

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

Laravel Eloquent 通過數據透視表加入

Laravel Eloquent 通過數據透視表加入

PHP
aluckdog 2022-01-24 10:08:59
不幸的是,我還沒有太多使用 Eloquent 的經驗。我嘗試從具有兩個數據透視表的三個表中創建一個查詢。我的桌子:我的模型:播放器class Player extends Model{    protected $table = 'players';    protected $fillable = [        'name'    ];    public function layout(){        return $this->belongsToMany('App\Layout', 'layout_player', 'player_id', 'layout_id');    }    public function information(){        return $this->hasMany('App\Information', 'player_id');    }}布局class Layout extends Model{    protected $table = 'layouts';    protected $fillable = [        'name'    ];    public function player(){        return $this->belongsToMany('App\Player', 'layout_player', 'layout_id', 'player_id');    }    public function item(){        return $this->belongsToMany('App\Item', 'item_layout', 'layout_id', 'item_id');    }}物品class Item extends Model{    protected $table = 'items';    protected $fillable = [        'name'    ];    public function layout(){        //return $this->hasOne(Layout::class);        return $this->belongsToMany('App\Layout', 'item_layout', 'item_id', 'layout_id');    }}從播放器開始,我想檢索當前播放器,所有布局和相應的項目。不幸的是我做不到。我調用播放器和布局如下:Player::where('id',1)->with('layout')->get();我如何另外獲取查詢中的所有項目?
查看完整描述

3 回答

?
茅侃侃

TA貢獻1842條經驗 獲得超21個贊

你完美地建立了關系。現在從 Player 到 layout 你得到了它with('layout')。試試看。

$players = Player::with('layout.item')->where('id',1)->get();

它將為您提供玩家以及帶有項目的布局。


查看完整回答
反對 回復 2022-01-24
?
嗶嗶one

TA貢獻1854條經驗 獲得超8個贊

如果我理解你的問題,我想你就快到了。


也將其添加到Player模型中,就像您所做的其他方法一樣。


public function contents(){

    return $this->belongsToMany('App\Content');

}

要獲取有關播放器的所有內容,請將這些內容寫入控制器并將其傳遞給查看文件。


$player = Player::findOrFail(1);

return view('path.to.file_name',compact('player'));

在視圖文件中


//get all contents of a player

@foreach($player->contents as $content)

    <p>{{ $content->text}}</p>

@endforeach


//get all layouts of a player

@foreach($player->layout as $layout)

    <p>{{ $layout->name}}</p>

@endforeach



//get all items of a player

@foreach($player->layout as $layout)

    <p>{{ $layout->name}}</p>

    @foreach($layout->item as $item)

        <p>{{ $item->name }}</p>

    @endforeach

@endforeach


查看完整回答
反對 回復 2022-01-24
?
滄海一幻覺

TA貢獻1824條經驗 獲得超5個贊

非常感謝您的快速回答。不幸的是,這并不能解決我的問題。我通過 api 路由調用 PlayerController 并需要表單中播放器的所有對象作為返回:

  • 播放器

  • 布局

  • 物品

public function show($id)

{

    $player = Player::findOrFail($id);

    //$player = Player::where('id',$id)->with('layout')->get();

    return $player;

}

我得到這個回應:


{"id":1,"name":"Testplayer","created_at":"2019-09-22 15:53:07","updated_at":"2019-09-22 15:53:07"}

但我還需要布局和項目。


我希望你仍然能理解我糟糕的英語。;)


查看完整回答
反對 回復 2022-01-24
  • 3 回答
  • 0 關注
  • 162 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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