Laravel Eloquent instead of Query Build



如何将以下Laravel(v8(Query转换为Eloquent?这是可能的吗?

'house_id' => DB::table('houses') ->select('id') ->where('user_id', Auth::user()->id) ->orderByDesc('created_at')->value('id')

目前的查询正在完成这项工作,但我很想知道Eloquent是否也能做到这一点。换句话说,还有一种更优雅的方式可以做到这一点吗?

如果我的问题一点道理都没有,我很抱歉。

非常感谢你的澄清。

Laravel在查询生成器上有一个latest()函数,它按created_at日期降序排列结果。因此,您可以将查询简化为以下内容:
House::where('user_id', Auth::user()->id)->latest()->first()->id;

这可能看起来很混乱,latest()->first(),但latest()返回一个collection,所以如果您使用first()访问最新的记录,然后从模型中获取id

如果你发现自己经常使用上面的内容,你可以更进一步,在你的User模型上定义一个scope

public function houses()
{
return $this->hasMany(House::class);
}
public function scopeLatestHouse(Builder $query) {
return $this->houses()->latest()->first();
}

现在你所需要做的就是:

$latestHouse = Auth::user()->latestHouse()->id;

如果您的模型名为House$house = House::query()->where('user_id', Auth::user()->getAuthIdentifier())->select('id')->orderBy('created_at', 'DESC')->get(),或者如果您只想获得一个元素,请使用->first()。然后您可以拨打$house->id

最新更新