简体   繁体   English

我如何在Eloquent中查询这种关系?

[英]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. 真的,我想通过他们喜欢的流派ID来获得Freestyle的集合。 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. 首先,您可以将流派的函数名称更改为beats()-仅出于约定,因为它将返回多个寄存器:P。 Second, with hasManyThrough you will get all Beats related (through Track) with Genre. 其次,通过hasManyThrough,您将获得与流派相关的所有Beats(通过Track)。 Then, you can access to the Freestyles related with that Beat: 然后,您可以访问与该Beat相关的自由式:

  • Create the relation in your Beat and Freestyle Model: 在Beat和Freestyle模型中创建关系:

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') 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. 希望对您有帮助。

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

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