withPivot
您可以通过关系函数上的函数指定它们来访问额外的数据透视表列。
基本上我认为你想这样做:
class User extends Eloquent {
public function games()
{
return $this->belongsToMany('Game', 'games_users')->withPivot('owntype_id');
}
}
class Game extends Eloquent {
public function users()
{
return $this->belongsToMany('User', 'games_users')->withPivot('owntype_id');
}
}
class Owntype extends Eloquent {
protected $table = 'owntype';
}
// Now you can do:
foreach ($user->games as $game)
{
// Echo each Owntype description.
echo Owntype::find($game->pivot->owntype_id)->description;
}
作为记录...我认为您可能会为owntype
. 只需将描述设置为type
数据透视表上的列即可。还要确保你的数据透视表被命名game_user
(单数,按字母顺序),Laravel 会自动知道要使用哪个数据透视表。
class User extends Eloquent {
public function games()
{
return $this->belongsToMany('Game')->withPivot('type');
}
}
class Game extends Eloquent {
public function users()
{
return $this->belongsToMany('User')->withPivot('type');
}
}
// Now you can do:
foreach ($user->games as $game)
{
// Echo each ownership type.
echo $game->pivot->type;
}
可以在Laravel 4 文档中找到有关使用数据透视表的更多信息。