Laravel与数据透视表中的列成多对多

时间:2018-10-20 09:07:04

标签: laravel pivot relationship

我有3张桌子: 工人,付款和私人 私人可以支付一个或多个工人的费用,而该工人可以从一个或多个私人获得付款。 付款表包含2个外键和金额。 如何使用laravel在3个表中创建关系以获取数据库中的所有信息? 例如,我想为每个工人从每个私人那里获得他所支付的金额。

2 个答案:

答案 0 :(得分:0)

我假设您已经了解laravel关系。

Worker.php

public function privates()
{
    return $this->belongsToMany('App\Private')->withPivot('amount');
}

Private.php

public function workers()
{
    return $this->belongsToMany('App\Worker')->withPivot('amount');
}

然后在您的控制器中

$private = Private::create();
$worker = Worker::create();
$amount = 1000;
$private->workers()->attach($worker->id, ['amount' => '$amount']);
                                            ^^^-column in your payment table.

答案 1 :(得分:0)

这是您定义many to manyWorker之间的Private关系的方式

工人模型

public function privates()
{
    return $this->belongsToMany(Private::class, 'payments', 'worker_id', 'private_id')
        ->withPivot('amount');
}

私有模型

public function workers()
{
    return $this->belongsToMany(Worker::class, 'payments', 'worker_id', 'private_id')
        ->withPivot('amount');
}

这是您如何检索privates的所有worker

控制器功能

$privates = $worker->privates;
// this '$privates' contains the 'pivot' table values which contains the 'amount'.

这是节省金额的方式。

控制器功能

// first $private and $worker need to have saved.
// and then attach particular $worker as below.
$private->attach($worker_id, ['amount' => 1200.00]);