我有一个链接模型,每个链接都有一个所有者(由DB中的ownerId表示,它是User表的外键)。
这里是链接模型:
<?php namespace App\Http\Models;
use Illuminate\Database\Eloquent\Model;
class Link extends Model {
protected $table = "Link";
// ...
// Relationships
public function owner()
{
return $this->belongsTo(User::class, 'ownerId', 'id');
}
}
当我在LinkController中使用$data = Link::find($linkId)->toJson();
时,包含所有者,但在JSON数据中为null。我也尝试过$data = Link::with('owner')->find($linkId)->toJson();
和$data = Link::find($linkId)->load('owner')->toJson();
并且当我使用$data = Link::find($linkId)->owner->toJson();
时,我得到了用户数据。我的代码中缺少什么吗?
是否有一种方法可以将所有者加载到链接对象中,并通过JSON获得它,而无需其他请求/步骤?
我终于找到了问题。我的用户表中的主键不是标准键(它是字符串键而不是int)。我在用户模型中添加了以下几行:
public $incrementing = false;
public $keyType = 'string';
现在$data = Link::with('owner')->find($linkId);
正常工作。
$ data = Link :: with('owner')->查找($ linkId)-> get();