我有两种模式:
Deal
- id
- seller
- buyer
- price
- date
Person
- id
- name
- balance
- email
Deal
模型字段seller
和buyer
包含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'...
我做错了什么?
答案 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();