简体   繁体   中英

How can I query this sort of relationship in Eloquent?

The schemas go as following:

Likes
id (pk)
UserID
FreestyleID    

Freestyle:
id (pk)
BeatId

Beat:
id (pk)
trackId

Track:
id (pk)
GenreId

Genre:
id (pk)
Title

Really I would like to get a collection of Freestyles by their genre ID where they have likes. I have tried quite a few things including relationships such as:

Genre model:
public function beat()
{
    return $this->hasManyThrough('App\Beat', 'App\Track', 'GenreId', 'TrackId');
}

However, the above will return results like the following because each track can have up to three beats.: 结果

Let me know if you need to see anything more.

you are on the correct way, but you will need a bit more of code. First of all, you can change your Genre's function name to beats() - just for convention, because it will return multiple registers :P. Second, with hasManyThrough you will get all Beats related (through Track) with Genre. Then, you can access to the Freestyles related with that Beat:

  • Create the relation in your Beat and Freestyle Model:

Beat:

public function freestyles()
{
    return $this->hasMany('App\Freestyle');
}

FreeStyle:

public function beat()
{
    return $this->belongsTo('App\Beat');
}

public function likes()
{
    return $this->hasMany('App\Like');
}
  • Get the related Freestyles that have Likes with:

has('freestyles.likes')

So, you can do a function like this (Genre Model):

public function beatsWithLikes()
{
    return $this->beats()->has('freestyles.likes');
}

I hope It helps you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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