2 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊
您最好在其中添加一個(gè)type屬性Creadorwith 'artista'/ 'autor'。
多態(tài)關(guān)系只能采用單一模型。所以你的代碼會(huì)變成:
public function creadors()
{
// Return a general relation for all 'creadores'.
return $this->morphedByMany(App\Creador::class, 'creador', 'creaciones');
}
public function artistas()
{
// Filter for 'artista's.
return $this->creadors()->where('type', 'artista');
}
public function autores()
{
// Filter for 'autor's.
return $this->creadors()->where('type', 'autor');
}

TA貢獻(xiàn)2037條經(jīng)驗(yàn) 獲得超6個(gè)贊
用下面的方法解決了。將關(guān)系從多態(tài)多對(duì)多更改為普通多對(duì)多,添加withPivot和wherePivot。
克里多爾模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Creador extends Model
{
protected $table = 'creators';
public function libros()
{
return $this->belongsToMany('App\Libro', 'creaciones')->withPivot('creador_type');
}
// All books as an Artist
public function librosArtista()
{
return $this->libros()->wherePivot('creador_type', 1);
}
// All books as an Author
public function librosAutor()
{
return $this->libros()->wherePivot('creador_type', 2);
}
}
Libro 模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use ChrisKonnertz\BBCode\BBCode;
class Libro extends Model
{
protected $table = 'libros';
public function creador()
{
return $this->belongsToMany('App\Creador', 'creaciones')->withPivot('creador_type');
}
// All book artists
public function artistas()
{
return $this->creador()->wherePivot('creador_type', 1);
}
// All book authors
public function autores()
{
return $this->creador()->wherePivot('creador_type', 2);
}
}
當(dāng)創(chuàng)建一個(gè)附加Creador到 a 時(shí)Libro:
$libro->artistas()->attach( $creador, [
'creador_type' => 1
]);
- 2 回答
- 0 關(guān)注
- 163 瀏覽
添加回答
舉報(bào)