簡體   English   中英

Laravel Eloquent 通過 pivot 表加入

[英]Laravel Eloquent join throug pivot tables

不幸的是,我對 Eloquent 還沒有太多經驗。 我嘗試從具有兩個 pivot 表的三個表中創建一個查詢。

我的桌子:

在此處輸入圖像描述

我的模型:

播放器

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();

我如何另外獲取查詢中的所有項目?

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

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

public function contents(){
    return $this->belongsToMany('App\Content');
}

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

$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

非常感謝您的快速回答。 不幸的是,這並不能解決我的問題。 我通過 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"}

但我還需要布局和項目。

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

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

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

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

暫無
暫無

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

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