Laravel的下落返回意外结果

发布于 2025-01-22 15:03:38 字数 3425 浏览 0 评论 0原文

我有2个桌子艺术家和艺术品。其结构是:

ID

名称年龄1
JoeBlogg2 22
2Bob Duff34
3Mark Smith25

Artworks

ID标题出售价格Artist Artist Artist_id
1Flowers180.001
2植物150.002
3Boxes0100.002
3螺纹0110.003

艺术家 艺术品有关系

public function artworks()
{
    return $this->hasMany(Artwork::class);
}

艺术家模特我与艺术品模型中的

public function artist()
{
    return $this->belongsTo(Artist::class);
}

,我与我想退还所有出售艺术品的艺术家的艺术家有关系(出售为1),是卖艺术品的Ans Ans价格的名称。我正在使用的雄辩的查询是:

 $artists = Artist::with('artworks')->whereRelation('artworks','sold','=',1)->get();

这确实选择了所有售出艺术品的艺术家。但是,如果艺术家既有售出的艺术品,又有未售出的艺术品,则可以返回两者。因此查询将返回:

ID名称标题出售价格Artistes_id
1Joe Blogg180.001
2Bob Duff植物150.002
3Bob DuffBoxes0100.002

当尚未出售带有标题框的艺术品时,不应在结果

如何获得它,以便我只返回出售艺术品?

I have 2 tables Artists and Artworks. The structure of which are:

Artists

idnameage
1Joe Blogg22
2Bob Duff34
3Mark Smith25

Artworks

idtitlesoldpriceartist_id
1flowers180.001
2plants150.002
3boxes0100.002
3threads0110.003

In the Artist Model I have a relation to artworks

public function artworks()
{
    return $this->hasMany(Artwork::class);
}

In the Artwork Model I have the relation to artists

public function artist()
{
    return $this->belongsTo(Artist::class);
}

I want to return all the artists with that have sold an artwork (sold is 1) and the name of the ans price of the sold artwork. The eloquent query I am using is:

 $artists = Artist::with('artworks')->whereRelation('artworks','sold','=',1)->get();

This does select all the Artists with sold artwork. However, if the artist has both a sold artwork and an unsold artwork it returns both. so the query would return:

idNamestitlesoldpriceartist_id
1Joe Bloggflowers180.001
2Bob Duffplants150.002
3Bob Duffboxes0100.002

When the artwork with the title Boxes has not been sold, so should not be in the results

How do I get it so that I only return sold artworks?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

玩套路吗 2025-01-29 15:03:38

感谢科迪

几乎取得了正确的答案 - 但是现在,无论他们是否出售艺术品,我现在都会吸引所有艺术家。尽管该子查询现在仅选择出售艺术品。

我已经将下落添加到您的答案中,现在它可以工作

$artists = Artist::with(['artworks' => function($query) {$query->where('sold', 1);}])->whereRelation('artworks','sold','=',1)->get();

Thanks Cody Brew

Almost the right answer - but I am now getting all Artists whether they've sold an Artwork or not. Although the subquery now only selects sold Artwork.

I have added back the whereRelation to your answer and it now apperas to work

$artists = Artist::with(['artworks' => function($query) {$query->where('sold', 1);}])->whereRelation('artworks','sold','=',1)->get();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文