简体   繁体   English

渴望在laravel 5中加载具有多个关系的两个表

[英]Eager loading two tables with multiple Relationships in laravel 5

I have 3 models Tracktype, Tracks and Subgenres . 我有3个模型Tracktype,Tracks和Subgenre。 The relationship is like this . 关系就是这样。 A Tracktype has many tracks and a track can have many subgenres . Tracktype有很多轨道,一个轨道可以有很多子流派。 but a track can only have one track type 但一条轨道只能有一种轨道类型

I have already defined relationships like these 我已经定义了像这样的关系

/**
 * Gets the tracks lists Associated with a track type
 *
 * @return \Illuminate\Database\Eloquent\Relations\hasMany
 */
public function tracks()
{
    return $this->hasMany('App\Tracks', 'id', 'id');
}


/**
 * Get the Lists of tracks Associated with the Subgenre ID
 *
 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
 */
public function tracks()
{
    return $this->belongsToMany('App\Tracks', 'subgenre_track', 'subgenre_id', 'track_id');
}

I have tried something like this . 我已经尝试过这样的事情。

App\TrackType::with(['tracks.subgeneres' => function ($query) {
    $query->where('name', 'Trans');
}])->where('name', 'Single')->get();

But it's not returning the correct results 但是它没有返回正确的结果

Array
(
    [0] => Array
        (
            [query] => select * from `tracktype` where `name` = ?
            [bindings] => Array
                (
                    [0] => Single
                )

        [time] => 0.55
    )

[1] => Array
    (
        [query] => select * from `tracks` where `tracks`.`id` in (?)
        [bindings] => Array
            (
                [0] => 1
            )

        [time] => 0.45
    )
)

My need is to get all tracks which are matching Tracktype of Single and Subgeneres matching Trans . 我需要获取所有与Single匹配的Tracktype和与Trans匹配的子类型的Track。 I have both Tracktype table and Subgeneres table along with relevant pivot tables. 我同时拥有Tracktype表和Subgeneres表以及相关的数据透视表。

How to define these relationships? 如何定义这些关系?

Fixed the issue by Changing method in Tracktype from hasMany to belongToMany . 通过将Tracktype中的方法从hasMany更改为归属ToMany来解决此问题。 And That was it .Used the Same Query :) 就是这样。使用相同的查询:)

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

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