简体   繁体   中英

laravel polymorphic relation assign model

I have a polymorphic relation

codes (code, soure_id, source_type)

sources:

websites (id, url)

books (id, isbn)

I have the necessary relations (morphTo, morphMany) coded in the models.

How can I assign a source to a code:

$source = Book::first();

    $code = new Code()
    $code->code = 'huxawex123ad'
    $code->source ... // How can I assign the book as the source?
    $code->save();

relations:

class Code extends Eloquent {
    public function source()
    {
        return $this->morphTo();
    }
};

class Book extends Eloquent {
    public function codes()
    {
        return $this->morphMany(Code::class, 'source');
    }
};

I dont's see proper fields set for polymorphic relationships

Add these fields to codes table:

sourceable_id - integer
sourceable_type - string

Relationships would be like:

 class website extends Model
 {
  /**
  * Get all of the website's codes.
  */
  public function codes()
  {
     return $this->morphMany('App\Code', 'sourceable');
  }
}

Then in your controllers:

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

MorphTo relationships are similar to BelongsTo relationships. So, assuming your Code model has a source() method setup to return a morphTo() relationship, your code would look like:

$source = Book::first();

$code = new Code()
$code->code = 'huxawex123ad'
$code->source()->associate($source);
$code->save();

Additionally, assuming your Book model had a codes() method setup to return a morphMany() relationship, your code could clean up like so:

$source = Book::first();

$source->codes()->create(['code' => 'huxawex123ad']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM