如何在Laravel Eloquent中指定多个一对一关系?

时间:2017-05-10 02:42:05

标签: php database laravel eloquent

我有两种模式:

Deal
 - id
 - seller
 - buyer
 - price
 - date

Person
 - id
 - name
 - balance
 - email

Deal模型字段sellerbuyer包含Person个模型实例。

在Laravel Eloquent中指定此模型的正确方法是什么?

我试着这样做。数据库架构:

deals
 - id: int, primary
 - seller_id: int
 - buyer_id: int
 - price: decimal(10, 2)
 - date: datetime

people
 - id: int, primary
 - name: string
 - balance: decima(10, 2)
 - email: string

雄辩的模特定义:

class Deal extends Model
{
    public function seller()
    {
        return $this->belongsTo(Person::class, 'seller_id');
    }

    public function buyer()
    {
        return $this->belongsTo(Person::class, 'buyer_id');
    }
}

class Person extends Model
{
    //
}

但是当我尝试创建一个新的Deal实例时:

$seller = new Person();
$seller->name = 'Anna';
$seller->balance = 100500;
$seller->email = 'anna@exampe.com';

$buyer = new Person();
$buyer->name = 'Bob';
$buyer->balance = 9000;
$buyer->email = 'bob@exampe.com';

$deal = new Deal();
$deal->seller = $seller;
$deal->buyer = $buyer;
$deal->price = 99.99;
$deal->date = new Carbon();

$deal->save();

我收到错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'buyer' in 'field list'...

我做错了什么?

2 个答案:

答案 0 :(得分:1)

当您说$deal->seller时,它会返回People对象的实例,因为您已经以这种方式定义了关系。但是在保存的同时,你可以做到这一点。试试这个

$seller = new Person();
$seller->name = 'Anna';
$seller->balance = 100500;
$seller->email = 'anna@exampe.com';
$seller->save(); // important

$buyer = new Person();
$buyer->name = 'Bob';
$buyer->balance = 9000;
$buyer->email = 'bob@exampe.com';
$buyer->save(); // important

$deal = new Deal();
$deal->seller_id = $seller->id;
// or $deal->seller()->associate($seller);
$deal->buyer_id = $buyer->id;
// or $deal->buyer()->associate($buyer);
$deal->price = 99.99;
$deal->date = new Carbon();

$deal->save();

答案 1 :(得分:1)

对于Belongs To Relationship,您应该使用associate方法。

您还需要先保存Person模型,以便在数据库中拥有相关的有效ID。

$seller = new Person();
$seller->name = 'Anna';
$seller->balance = 100500;
$seller->email = 'anna@exampe.com';
$seller->save();

$buyer = new Person();
$buyer->name = 'Bob';
$buyer->balance = 9000;
$buyer->email = 'bob@exampe.com';
$buyer->save();

$deal = new Deal();
$deal->seller()->associate($seller);
$deal->buyer()->associate($buyer);
$deal->price = 99.99;
$deal->date = new Carbon();

$deal->save();