状況
下記の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: "トースト"
},
...