[英]Laravel 8.x realationship - Use HasMany in HasOne
我正在嘗試在HasOne
中使用HasMany
關系。
我有以下型號:
class Auction extends Model
{
//...
public function bids(): HasMany
{
return $this->hasMany(Bid::class, 'auction_id');
}
public function approvedBids(): HasMany
{
return $this->bids()->approved();
}
public function topBids(): HasMany
{
return $this->approvedBids()->orderByDesc('price')->take(10);
}
public function topBid(): HasOne
{
//return $this->topBids()->firstOfMany(); // Not Working
//return $this->hasOne(Bid:class, 'auction_id)->ofMany('price','max')->approved(); // not working
//return $this->hasOne(Bid:class, 'auction_id)->approved()->ofMany('price','max'); // not working
//return $this->hasOne(Bid::class, 'auction_id')->ofMany('price', 'max'); // working but not as I expecting
}
}
class Bid extends Model
{
//...
public function scopeApproved(Builder $query): Builder
{
return $query->where('state', BidState::STATE_APPROVED);
}
//...
}
正如您在源代碼中看到的那樣,我正在尋找一種方法來建立從topBids()
關系中檢索最高出價(ONE BID)的關系,但我不知道如何,而且我的方法都不起作用:
$this->topBids()->firstOfMany(); // Not Working
$this->hasOne(Bid:class, 'auction_id')->ofMany('price','max')->approved(); // not working
$this->hasOne(Bid:class, 'auction_id')->approved()->ofMany('price','max'); // not working
不幸的是,這些不應該是一種關系
真正的問題是你為什么要建立這些關系?
通常,您應該使用 model 上的關系來描述它們在數據庫中如何相互關聯,您應該將 rest 定義為查詢中的 scope 或 model,或作為屬性。
所以,我想說的是:
bids
為關系,因為這實際上是與Bid
model 的關系approvedBids
更新為 scope(或屬性)topBids
更新為 scope(或屬性)然后,您將能夠通過執行以下操作輕松找到最高出價:
$this->topBids->first()
-> 如果它是一個屬性$this->topBids()->first()
-> 如果它是 scope這是創建 scope 的方法: https://laravel.com/docs/9.x/eloquent#local-scopes
最后,您甚至可以創建一個屬性,允許您像這樣檢索topBid
:
public function getTopBidAttribute(){
$this->bids()->approved()->orderByDesc('offered_token_price')->first();
}
然后你可以做$this->topBid
。
我想我找到了解決方案
public function topBid(): HasOne
{
return $this->hasOne(Bid::class, 'auction_id')
->approved()
->orderByDesc('price');
}
你看問題出在ofMany()
function 中,它創建了一個巨大的SQL
,我不知道為什么!
我這里返回了一個HasOne
object,支持各種查詢操作。 基本上HasOne
class 告訴主要查詢:
檢索我提供的查詢的第一條記錄。
因此,如果我們使用orderBy
,它只會為HasOne
的查詢提供一個順序。 主查詢將處理 rest 並選擇第一條記錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.