laravel多态关系分配模型

时间:2017-12-28 20:48:28

标签: laravel eloquent

我有多态关系

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

2 个答案:

答案 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']);