简体   繁体   English

Laravel中表之间的雄辩关系

[英]Eloquent Relationship Between Tables in Laravel

I have three tables: 我有三个表:

  1. collections which has id , name 具有idname collections
  2. genre_collection which has id , genre_id , collection_id genre_collection其中有idgenre_idcollection_id
  3. genres which has id , name 具有idname genres

I want to retrieve data from collections with generes. 我想从具有类型的集合中检索数据。

Collections Model 集合模型

class Collections extends Model{
    public function genres(){
        return $this->hasMany('App\Models\GenreCollectionRelationships', 'genre_id' , 'id');
    }
}

generic_collection generic_collection

class GenreCollectionRelationships extends Model{
    public function genre(){
        return $this->hasOne('App\Models\Genres', 'id', 'genre_id');
    }
}

Search Controller 搜索控制器

class SearchController extends Controller{
    $collection->genres;
    foreach($collection->genres as $item){
        $item->genre;
    }
}

This code is working fine. 这段代码工作正常。 And the output is 输出是

Actual 实际

"genres": [{
    "id": 1,
    "genre_id": 1,
    "collection_id": 1,
    "created_at": "2019-02-07 17:13:36",
    "updated_at": "2019-02-07 17:13:36",
    "genre": {
        "name": "Action",
        "meta": null
    }
}]

Is there any way i could directly get the output as shown below 有什么办法可以直接获得输出,如下所示

Expected 预期

"genres": [ {
    "name": "Action",
    "meta": null
}]

I tried hasManyThrough, belongsToMany but nothing worked out. 我尝试过hasManyThrough,belongsToMany,但没有任何结果。

Note. 注意。 I am on laravel 5.7 我在laravel 5.7上

Thanks in advance. 提前致谢。

You could build your own query to achieve what you are looking for. 您可以构建自己的查询以实现所需的内容。 Try this: 尝试这个:

$collection = Collection
        ::join('genres', 'genre.id', '=', 'collections.genre_id')
        ->select('collections.*', 'genres.name','genre.meta')
        ->get();

I find your code a bit hard to follow... Let me try and see if I understood it correctly... 我发现您的代码有点难以遵循...让我尝试看看我是否正确理解了...

You basically have two models: 您基本上有两个模型:

  • Model Collection saved in table collections 模型Collection保存在表collections
  • Model Genre saved in table genres 模型Genre保存在表格genres

Since you have a many to many relationship between them, you need a third table to link the both of them together. 由于它们之间存在多对多关系,因此需要第三个表将两者链接在一起。

By naming convention, Laravel expects you to name it based on the two models, ordered alphabetically. 按照命名约定,Laravel希望您根据两个模型(按字母顺序)命名。 So to create a link between collections and genres, you would need to create a table collection_genre which has a collection_id as a reference to the collections table, and likewise a genre_id to identify the linked genre. 因此,要在馆藏和类型之间建立链接,您需要创建一个表collection_genre ,该表具有collection_id作为对collections表的引用,并且还具有genre_id以标识链接的类型。

You can then define your relationships as follows: 然后,您可以如下定义关系:

class Collection extends Model {
    public function genres() {
       $this->belongsToMany(\App\Models\Genre::class);
    }
}

and

class Genre extends Model {
    public function collections() {
       $this->belongsToMany(\App\Models\Collection::class);
    }
}

Now, I'm not sure what your controller looks like as the question has some invalid code to it, but I suspect you want to search the genres for a given collection. 现在,我不确定您的控制器是什么样的,因为问题中包含一些无效的代码,但是我怀疑您想搜索给定集合的类型。

Your code could like like this: 您的代码可能像这样:

Class CollectionController extends Controller {

    function getGenres(Collection $collection) {
        return $collection->genres;
    }
}

This would return the genres for the given collection. 这将返回给定集合的类型。 If you want to format this, you could create an Eloquent Resource for this: 如果要格式化它,可以为此创建一个雄辩的资源:

Class CollectionResource extends Resource {
    public function toArray() {
        return [
           'name' => $this->name,
           'meta' => $this->meta
        ];
    }
}

In your controller you can then do: 然后,您可以在控制器中执行以下操作:

Class CollectionController extends Controller {

    function getGenres(Collection $collection) {
        return CollectionResource::collection($collection->genres);
    }
}

in your collection model 在您的收藏模型中

class Collections extends Model
{
    protected $table='collections';
    public $primaryKey='id';
    protected $fillable = ['name'];

    public function genres()
     {
            return $this->belongsToMany('App\Model\Genres','genre_collection','collection_id','genre_id')->withTimestamps();
     }

}

in your genres model 在您的流派模型中

class Genre extends Model {

  protected $table='genres';
  public $primaryKey='id';
  protected $fillable = ['name'];


    public function collections()
    {
        return $this->belongsToMany('App\Model\Collections','genre_collection','genre_id','collection_id')->get();
    }

}

You are creating many to many relationship between collections and genre using genre_collection pivot table. 您正在使用genre_collection数据透视表在collectionsgenre之间建立多对多关系。 In that case, belongsToMany is appropriate. 在这种情况下, belongsToMany是合适的。 And you don't need any model for genre_collection table. 而且您不需要genre_collection表的任何模型。

Collections model 集合模型

class Collections extends Model
{
    public function genres(){
        return $this->belongsToMany('App\Models\Genres', 'genre_collection', 'genre_id', 'collection_id');
    }
}

Genres model 流派模型

class Genres extends Model
{

    public function collections(){
        return $this->belongsToMany('App\Models\Collections', 'genre_collection', 'collection_id', 'genre_id');
    }
}

SearchController SearchController

class SearchController extends Controller
{
    foreach($collection->genres as $item){
        $item->genre; // get genre info
    }
}

I'm assuming that you want to access Generic directly from collection . 我假设您想直接从collection访问Generic。 If this is the case you can define a many-to-many relationship in collection model directly to generic model to access it . 如果是这种情况,您可以在集合模型中直接定义一个多对多关系来访问通用模型。 Please refer this : https://laravel.com/docs/5.7/eloquent-relationships#many-to-many . 请参考: https : //laravel.com/docs/5.7/eloquent-relationships#many-to-many Sorry if I'm wrong 对不起,如果我错了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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