[英]Relations Laravel 4 with 3 tables using Eloquent
我想使用 ORM 与 3 个表建立关系但不能。 我的桌子
用户表
id | userame | name |
1 Ellie Elen
2 Pol Paul
记录表
id | user_id| item_id| hour|
1 2 1 3
2 2 2 5
项目表表
id | title
1 item 1
2 item 2
我正在使用此逻辑但无法正常工作
class User Extends Eloquent {
public function record()
{
return $this->hasMany('VolunteerRecord');
}
}
class VolunteerRecord Extends Eloquent {
function item() {
return $this->hasMany('VolunteerItem');
}
}
我不明白该怎么做?
看起来您想要Users
和Items
之间的多对多关系,但您还想在数据透视表上跟踪小时数。 所以首先,您将使用belongsToMany()
定义多对多关系,然后您将使用withPivot()
函数告诉 Laravel 您的数据透视表上有额外的数据。 您的课程将如下所示:
class User extends Eloquent {
protected $table = 'users';
public function items() {
return $this->belongsToMany('Item', 'records')->withPivot('hour');
}
}
class Item extends Eloquent {
protected $table = 'items';
public function users() {
return $this->belongsToMany('User', 'records')->withPivot('hour');
}
}
然后,要访问hour
字段,您可以这样做:
$user = User::first(); // First User
$item = $user->items()->first(); // User's first Item
$hour = $item->pivot->hour; // The 'hour' on the User-Item relationship
此外,您当前的列命名方案对于 Laravel 是正确的,因此您不需要更改它。 如果更改列名,则需要在belongsToMany()
方法中定义它们,如下所示:
$this->belongsToMany('ModelName', 'pivot_table', 'foreign_key', 'other_key');
// For example, in Items::users() you would have this:
$this->belongsToMany('User', 'records', 'users_id', 'items_id');
最后,我假设您的表被命名为users
、 items
和records
。 如果不是,则只需将users
、 items
和records
的所有实例替换为您的实际表名。
根据您的表名,我建议如下,首先,按如下方式更改您的记录表:
id | users_id| items_id| hour|
1 2 1 3
2 2 2 5
这些是您的模型的类:
class Users extends Eloquent
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
public function records()
{
return $this->hasMany('Records');
}
}
class Records extends Eloquent
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'records';
public function record()
{
return $this->hasOne('Users');
}
public function item()
{
return $this->hasOne('Items');
}
}
class Items extends Eloquent
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'items';
public function records()
{
return $this->hasMany('Records');
}
}
这些包含您的模型的关系。 如果您要选择几条记录,对于每条记录,您可以获得用户和项目。 如果您要选择一个项目,以及该项目的所有记录。 您还可以获取每条记录的用户。
在用户模型中
public function images()
{
return $this->belongsToMany('Item')->withPivot('hour');
}
在用户控制器中
public function view($username)
{
$user = User::where('name',$username)->firstOrFail();
return View::make('view')->with('user',$user);
}
在视图中
@foreach ($users->items as $item)
name: {{$image->title}}<br>
hour: {{$image->pivot->hour}}<br>
@endforeach
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.