Laravel Eloquent "with" / "load" return 空
Laravel Eloquent "with" / "load" return null
我正在尝试使用 with
方法获得关系(产品所有者),但它 returns 我 null
.
经过一些测试后,我发现如果我使用简单的方法来获取它(例如 $goodRelation
),我的关系是可以的,但是如果我试图以任何方式与 with
方法建立关系 returns 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
模特:
public function goods()
{
return $this->hasMany(Good::class);
}
我的Good
模特:
public function user()
{
return $this->belongsTo(User::class);
}
实例中的问题:
为什么我无法与 load
方法的 with
建立关系?
解决方案:如果您正在使用 uuid
或 not default integer
- 您应该在模型中设置 $keyType
。
class Flight extends Model
{
/**
* The "type" of the auto-incrementing ID.
*
* @var string
*/
protected $keyType = 'string';
}
来自 Laravel 7 文档;
If your primary key is not an integer, you should set the protected $keyType property on your model to string:
<?php
class Flight extends Model
{
/**
* The "type" of the auto-incrementing ID.
*
* @var string
*/
protected $keyType = 'string';
}
我正在尝试使用 with
方法获得关系(产品所有者),但它 returns 我 null
.
经过一些测试后,我发现如果我使用简单的方法来获取它(例如 $goodRelation
),我的关系是可以的,但是如果我试图以任何方式与 with
方法建立关系 returns 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
模特:
public function goods()
{
return $this->hasMany(Good::class);
}
我的Good
模特:
public function user()
{
return $this->belongsTo(User::class);
}
实例中的问题:
为什么我无法与 load
方法的 with
建立关系?
解决方案:如果您正在使用 uuid
或 not default integer
- 您应该在模型中设置 $keyType
。
class Flight extends Model
{
/**
* The "type" of the auto-incrementing ID.
*
* @var string
*/
protected $keyType = 'string';
}
来自 Laravel 7 文档;
If your primary key is not an integer, you should set the protected $keyType property on your model to string:
<?php
class Flight extends Model
{
/**
* The "type" of the auto-incrementing ID.
*
* @var string
*/
protected $keyType = 'string';
}