[英]Laravel Eloquent “with” / “load” return null
我正在嘗試使用with
方法獲得理性(產品所有者),但它返回給我null
。
經過一些測試后,如果我使用簡單的方法來獲取它(例如$goodRelation
),我發現我的關系沒問題,但是如果我試圖with
方法獲取關系,它會以任何方式返回null
EXAMPLES
$goodWith = Good::where('id', '4d7d36f2-75ad-4a9f-a5a5-ba8b56840414')->with('user')->first()->user;
$goodsLoad = Good::where('id', '4d7d36f2-75ad-4a9f-a5a5-ba8b56840414')->first()->load('user')->user;
$goodFirstUserFirst = Good::where('id', '4d7d36f2-75ad-4a9f-a5a5-ba8b56840414')->first()->user()->first();
$goodsRelation = Good::where('id', '4d7d36f2-75ad-4a9f-a5a5-ba8b56840414')->first()->user;
dd($goodWith, $goodsLoad, $goodFirstUserFirst, $goodsRelation);
結果:
$goodWith -> NULL
$goodsLoad -> NULL
$goodFirstUserFirst -> USER MODEL
$goodsRelation -> USER MODEL
我的User
model:
public function goods()
{
return $this->hasMany(Good::class);
}
我的Good
model:
public function user()
{
return $this->belongsTo(User::class);
}
為什么我無法with
load
方法建立關系?
來自 Laravel 7 文檔;
如果您的主鍵不是 integer,則應將 model 上的受保護 $keyType 屬性設置為字符串:
<?php
class Flight extends Model
{
/**
* The "type" of the auto-incrementing ID.
*
* @var string
*/
protected $keyType = 'string';
}
解決方案:如果您使用uuid
或not default integer
- 您應該在 model 中設置$keyType
keyType。
class Flight extends Model
{
/**
* The "type" of the auto-incrementing ID.
*
* @var string
*/
protected $keyType = 'string';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.