2016-03-27 68 views
0

对象Page有任何数量的Widgets和每个Page-Widget对有特殊选项(例如,位置,自定义标题)。Laravel:belongsToMany与其他字段

我只是做了

class Page extends Model { 
    public function widgets(){ 
     return $this->belongsToMany('App\Widget'); 
    } 
} 
... 
class Widget extends Model { 
} 

我增加了更多的列page_widget表(位置,设置...)。

如何通过$page->widget->position访问/更新它们?我还需要按照position排序页面小部件的功能。

请建议模型关系。谢谢。

+0

假设你有一个多对多的关系,你有一个名为'pages_widget'的数据透视表。您可以将列添加到该表并使用“pivot”访问值。在[文档](https://laravel.com/docs/5.1/eloquent-relationships)上查看多对多关系的最后部分(即检索中间表列) –

+0

只需添加到@milz评论。 _pivot table_只是一个_join table_,它有多个列(例如''position')。 – Michael

回答

1

您可以添加额外的字段是这样的:

class Page extends Model { 
    public function widgets(){ 
     return $this->belongsToMany('App\Widget')->withPivot('position', 'settings); 
    } 
} 

然后,要创建在数据库这一行,你这样做:

$page->widgets()->attach($widgetId, ['position' => $position, 'settings' => $settings]); 

要访问的数据透视表的数据,你可以这样做:

foreach ($page->widgets as $widget) { 
    echo $widget->pivot->position; 
    echo $widget->pivot->settings; 
} 

官方文档中有很多信息:https://laravel.com/docs/5.2/eloquent-relationships#many-to-many