我對如何正確地從 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());// WRONG: returns first country in the database and not the one with ID of 32, relationship is also not correct, EXPECTED: object with selected country with valid relationship (clients) as array of objectsdd(Country::findOrFail(32)->clients());// WRONG: returns HasMany relationship, no data, EXPECTED: an array of clients as objectsdd(Country::findOrFail(32)->clients()->get());// CORRECT: returns valid data, array of clients as objectsdd(Country::findOrFail(32)->clients()->first());// CORRECT: returns first client for selected country
那么,為什么都是 WRONG 錯誤的呢?我是否錯誤地解釋了檔案?最令人沮喪的是dd(Country::with('clients')->findOrFail(32)->first()),現在我無法根據所選國家/地區進行過濾,然后還提供該國家/地區的客戶串列。我認為 Eloquent 非常先進,所以我認為我做錯了什么,希望得到一些指導。請注意,在最新的示例中,我還嘗試將查詢反轉為dd(Country::findOrFail(32)->with('clients')->first()),結果相同。
uj5u.com熱心網友回復:
在我看來,你在這里混淆了一些東西。例如,將 FindOrFail() 與 first() 結合使用是雙重的。看這里,這是我發現的一個很好的解釋:
find($id)接受一個 id 并回傳一個模型。如果不存在匹配的模型,則回傳 null。findOrFail($id)接受一個 id 并回傳一個模型。如果不存在匹配的模型,則會拋出錯誤 1。first()回傳在資料庫中找到的第一條記錄。如果不存在匹配的模型,則回傳 null。firstOrFail()回傳在資料庫中找到的第一條記錄。如果不存在匹配的模型,則會拋出錯誤 1。get()回傳與查詢匹配的模型集合。pluck($column)僅回傳給定列中值的集合。在以前的 Laravel 版本中,這種方法被稱為串列。toArray()將模型/集合轉換為一個簡單的 PHP 陣列。
來源:https : //stackoverflow.com/a/33027466/14807111
uj5u.com熱心網友回復:
Builder 方法的方法描述FindOrFail()是:
* Find a model by its primary key or throw an exception.
在您的用例中,此方法正在呼叫該find()方法并執行:
$this->whereKey($id)->first($columns);
這將回傳第一個模型,默認情況下它的所有列。因此,任何其他first()之后都會引入另一個查詢。
您的前三個“錯誤”是因為執行順序,查詢首先執行 findOrFail,然后first()再次呼叫整個查詢。
第四個“錯誤”發生是因為您的關系回傳了一個 hasMany 關系,這是正常行為。您可以->get()事后致電或在->clients沒有 的情況下致電()以接收集合。
畢竟你使用的first()方法是錯誤的。您要么使用find(),findOrFail()要么使用->first(). 但是你不應該一起使用它們(可能有一些邊緣情況你必須,但從體裁上來說,不要!)。使用find()或findOrFail()將已經回傳與 匹配的 first() 元素ID。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/344476.html
