LoginSignup
5
5

More than 5 years have passed since last update.

belongsToManyで取得した結果からpivotテーブルの情報を除外する方法

Posted at

状況

下記のCafeとMenuの2つのModelがあります。

Cafe.php
class Cafe extends Eloquent
{
    protected $table = 'cafes';

    public function menus() 
    {
        return $this->belongsToMany('Menu', 'cafe_menus');
    }
}
Menu.php
class Menu extends Eloquent
{
    protected $table = 'menus';

    public function cafes()
    {   
        return $this->belongsToMany('Cafe', 'cafe_menus');
    } 
}

下記のControllerのように値を取得すると、、

CafeController.php
...
$cafe = Cafe::find($id);
$menus = $cafe->menus()->select('menus.id as id', 'name')->get();
...

不要なpivotテーブルの情報が含まれています。。

結果
menus: [
{
    id: 229,
    name: "トースト",
    pivot: {
        cafe_id: 673,
        menu_id: 229
    }
},
...

対応

先ほどの2つのテーブルにhiddenプロパティを設定してあげます。

Cafe.php
class Cafe extends Eloquent
{
    protected $hidden = array('pivot');
...
Menu.php
class Menu extends Eloquent
{
    protected $hidden = array('pivot');
...

今回の場合はMenuのModelに記載するだけで動作はするようですが、両方に記述しておくとよいでしょう。

結果
menus: [
{
    id: 229,
    name: "トースト"
},
...

参考

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5