簡體   English   中英

渴望在laravel 5中加載具有多個關系的兩個表

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

我有3個模型Tracktype,Tracks和Subgenre。 關系就是這樣。 Tracktype有很多軌道,一個軌道可以有很多子流派。 但一條軌道只能有一種軌道類型

我已經定義了像這樣的關系

/**
 * 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');
}

我已經嘗試過這樣的事情。

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

但是它沒有返回正確的結果

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
    )
)

我需要獲取所有與Single匹配的Tracktype和與Trans匹配的子類型的Track。 我同時擁有Tracktype表和Subgeneres表以及相關的數據透視表。

如何定義這些關系?

通過將Tracktype中的方法從hasMany更改為歸屬ToMany來解決此問題。 就是這樣。使用相同的查詢:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM