多对多(多态)使用具有不同类型的相同模型

时间:2019-09-06 02:01:26

标签: php laravel eloquent many-to-many

我在数据库中有以下3个表: Database

我正在使用多对多(多态)口才关系来连接模型。问题是Creadores表的类型可以是artista表中的autorCreaciones。 可以告诉Eloquent何时使用artistaautor吗?

如果我将Creador模型扩展到另外两个模型ArtistaAutor中,它将起作用。但是当我想使用creaciones模型显示creador的所有Creador时,那是不可能的,因为多态关系是用扩展模型创建的。

Libro型号:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use ChrisKonnertz\BBCode\BBCode;

class Libro extends Model
{
    protected $table = 'Libros';

    // Return all the artists of the book
    public function artistas()
    {
        return $this->morphedByMany('App\Creador', 'creador', 'creaciones');
    }

    // Return all the authors of the book
    public function autores()
    {
        return $this->morphedByMany('App\Creador', 'creador', 'creaciones');
    }
}

储物箱型号:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Creador extends Model
{
    protected $table = 'creators';

    // Return all the books where author
    public function autorLibros()
    {
        return $this->morphToMany('App\Libro', 'creador', 'creaciones');
    }

    // Return all the books where artist
    public function artistaLibros()
    {
        return $this->morphToMany('App\Libro', 'creador', 'creaciones');
    }
}

2 个答案:

答案 0 :(得分:1)

您最好将type / Creador的{​​{1}}属性添加到'artista'

多态关系只能采用一个模型。 因此您的代码将变为:

'autor'

答案 1 :(得分:0)

通过以下方式解决。将withPivotwherePivot的关系从多态多对多关系更改为普通多对多关系。

餐车型号

<?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附加到Libro时:

$libro->artistas()->attach( $creador, [
    'creador_type' => 1
]);
相关问题