Laravel雄辩地通过透视表联接

时间:2019-09-23 11:00:00

标签: php laravel eloquent

不幸的是,我还没有关于Eloquent的丰富经验。我尝试从具有两个数据透视表的三个表中创建一个查询。

我的桌子:

enter image description here

我的模特:

玩家

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 个答案:

答案 0 :(得分:0)

如果我理解您的问题,我认为您快到了。

也将其添加到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

答案 1 :(得分:0)

非常感谢您的快速解答。不幸的是,这不能解决我的问题。 我通过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"}

但是我还需要布局和项目。

我希望你仍然能理解我的英语不好。;

答案 2 :(得分:0)

您建立了完美的恋爱关系。现在,从播放器到布局,您将得到with('layout')。试试吧。

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

它将为您提供球员以及物品的布局。