我正在尝试使用with
方法获得薪水(产品所有者),但返回的却是null
。
经过一些测试,我发现如果我使用简单的方法来获得关系(例如$goodRelation
),但是如果我试图使用with
的方法来获得关系,它会以任何方式返回{{ 1}}
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);
}
方法的with
建立联系?
答案 0 :(得分:1)
来自Laravel 7文档;
如果主键不是整数,则应将模型上受保护的$ keyType属性设置为字符串:
<?php
class Flight extends Model
{
/**
* The "type" of the auto-incrementing ID.
*
* @var string
*/
protected $keyType = 'string';
}
答案 1 :(得分:0)
解决方案:如果您使用的是uuid
或not default integer
-您应该在模型中设置$keyType
。
class Flight extends Model
{
/**
* The "type" of the auto-incrementing ID.
*
* @var string
*/
protected $keyType = 'string';
}