2 回答

TA贡献1802条经验 获得超5个赞
您最好在其中添加一个type属性Creadorwith 'artista'/ 'autor'。
多态关系只能采用单一模型。所以你的代码会变成:
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贡献2037条经验 获得超6个赞
用下面的方法解决了。将关系从多态多对多更改为普通多对多,添加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);
}
}
当创建一个附加Creador到 a 时Libro:
$libro->artistas()->attach( $creador, [
'creador_type' => 1
]);
- 2 回答
- 0 关注
- 164 浏览
添加回答
举报