我有多态关系
codes (code, soure_id, source_type)
来源:
websites (id, url)
books (id, isbn)
我在模型中编码了必要的关系(morphTo,morphMany)。
如何为代码分配来源:
$source = Book::first();
$code = new Code()
$code->code = 'huxawex123ad'
$code->source ... // How can I assign the book as the source?
$code->save();
关系:
class Code extends Eloquent {
public function source()
{
return $this->morphTo();
}
};
class Book extends Eloquent {
public function codes()
{
return $this->morphMany(Code::class, 'source');
}
};
答案 0 :(得分:1)
我没有看到为多态关系设置的正确字段
将这些字段添加到代码表:
sourceable_id - integer
sourceable_type - string
关系就像:
class website extends Model
{
/**
* Get all of the website's codes.
*/
public function codes()
{
return $this->morphMany('App\Code', 'sourceable');
}
}
然后在你的控制器中:
$source = Book::first();
$code = new Code()
$code->code = 'huxawex123ad'
$code->source ... // How can I assign the book as the source?
$code->save();
$source->codes()->save($code);
答案 1 :(得分:1)
MorphTo
关系类似于BelongsTo
关系。因此,假设您的Code
模型设置了source()
方法以返回morphTo()
关系,您的代码将如下所示:
$source = Book::first();
$code = new Code()
$code->code = 'huxawex123ad'
$code->source()->associate($source);
$code->save();
此外,假设您的Book
模型设置codes()
方法以返回morphMany()
关系,您的代码可以像这样清理:
$source = Book::first();
$source->codes()->create(['code' => 'huxawex123ad']);