【发布时间】:2021-12-15 12:27:33
【问题描述】:
我对如何正确地从 Eloquent 模型中提取数据有点困惑。我确实阅读了文档,但没有在任何地方提及,或者我错过了。
假设我们有两个模型,Client 和Country(注意:我只添加了相关代码,否则这个问题会很长):
客户:
<?php
namespace App\Models\Client;
use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* @property int id
* @property int country_id
*/
class Client extends BaseModel
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
...
'country_id',
...
];
/**
* Return Country relationship
*
* @return BelongsTo
*/
public function country(): BelongsTo
{
return $this->belongsTo(Country::class);
}
}
国家:
<?php
namespace App\Models\Country;
use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* @property int id
*/
class Country extends BaseModel
{
public function clients(): hasMany
{
return $this->hasMany(Client::class);
}
}
没什么特别的,两个普通模型。现在,当我尝试提取数据时,我遇到了一些问题:
-
dd(Country::findOrFail(32));// 正确:返回所选国家 -
dd(Country::findOrFail(32)->first());// 错误:返回数据库中的第一个国家,而不是 ID 为 32 的国家,预期:具有选定国家/地区的单个国家对象 -
dd(Country::findOrFail(32)->get());// 错误:返回数据库中的所有国家/地区,预期:包含一个国家/地区的对象数组 -
dd(Country::with('clients')->findOrFail(32)->first());// 错误:返回数据库中的第一个国家,而不是 ID 为 32 的国家,关系也不正确,预期:对象与选定国家的有效关系(客户)作为对象数组 -
dd(Country::findOrFail(32)->clients());// 错误:返回 HasMany 关系,无数据,预期:作为对象的客户端数组 -
dd(Country::findOrFail(32)->clients()->get());// 正确:返回有效数据,客户端数组作为对象 -
dd(Country::findOrFail(32)->clients()->first());// 正确:返回所选国家/地区的第一个客户
那么,为什么所有错误的都是错误的?我是否错误地解释了文档?最令人沮丧的是dd(Country::with('clients')->findOrFail(32)->first()),因为现在我无法根据选定的国家/地区进行过滤,然后还提供该国家/地区的客户列表。我认为 Eloquent 相当先进,所以我认为我做错了什么,并希望得到一些指导。
请注意,在最新示例中,我还尝试将查询反转为dd(Country::findOrFail(32)->with('clients')->first()),结果相同。
【问题讨论】: