gpt4 book ai didi

laravel - 通过 Laravel 4 中的关系属性进行查询

转载 作者:行者123 更新时间:2023-12-01 01:47:15 24 4
gpt4 key购买 nike

我在艺术家和专辑之间有这种一对多的关系,一个艺术家可以与许多专辑相关,但一张专辑只能与一个艺术家相关。

我的艺术家模型:

<?php


class Artist extends Eloquent {

public function albums()
{
return $this->hasMany('Album');
}

}

我的相册模型:

<?php


class Album extends Eloquent {

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

}

我学会了如何获取一个艺术家的所有专辑,以及检索专辑的艺术家。但我仍然不知道如何进行此查询:

Get all the albums whom artist is "Linkin Park"

我目前正在做的是:

$artist = Artist::where('name','=','Linkin Park')->first();

$albums = Album::where('artist_id','=',$artist->id)->get();

我得到了我需要的东西,但我想知道是否有其他方法可以做到这一点。类似(我知道是错误的):

$albums = Album::where('artist','=','Linkin Park');

最佳答案

没关系,我通过查看 examples in the official documentation 找到了一种方法.

查询应该是这样的:

$albums = Album::whereHas('artist', function($q)
{
$q->where('name', '=', 'Linkin Park');

})->get();

关于laravel - 通过 Laravel 4 中的关系属性进行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24474453/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com