【问题标题】:laravel polymorphic relation assign modellaravel 多态关系分配模型
【发布时间】:2017-12-29 17:01:24
【问题描述】:

我有一个多态关系

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

【问题讨论】:

    标签: laravel eloquent


    【解决方案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']);
    

    【讨论】:

    • 问题是,代码行已经存在。我需要添加关系而不是创建新的代码条目。
    • 并且关联失败:找不到类“voluptates”...即使该类应该是 App\Models\Book
    【解决方案2】:

    我没有看到为多态关系设置适当的字段

    将这些字段添加到代码表中:

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

    【讨论】:

    • 这就是我所拥有的。我错过了这一行:$code->source ... // 如何将这本书指定为来源?
    猜你喜欢
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-17
    • 2017-07-07
    • 2014-12-30
    • 1970-01-01
    相关资源
    最近更新 更多