关系Laravel 4与3个表使用雄辩


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

项目表table

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');
    }
}

我不明白该怎么做?

看起来您想要UsersItems之间的多对多关系,但您还想要跟踪数据透视表上的小时数。因此,首先,您将使用belongsToMany()定义多对多关系,并且您将告诉Laravel使用withPivot()函数在数据透视表上有额外的数据。你的类看起来像这样:

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');

最后,我假设您的表命名为usersitemsrecords。如果不是,那么只需将usersitemsrecords的所有实例替换为实际的表名。

根据您的表名,我建议如下:首先,按如下方式更改您的记录表:

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