如何与雄辩的人建立关系?

时间:2019-12-21 12:40:58

标签: php laravel eloquent lumen eloquent--relationship

我有一个链接模型,每个链接都有一个所有者(由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获得它,而无需其他请求/步骤?

2 个答案:

答案 0 :(得分:0)

我终于找到了问题。我的用户表中的主键不是标准键(它是字符串键而不是int)。 我在用户模型中添加了以下几行:

public $incrementing = false;
public $keyType = 'string';

现在$data = Link::with('owner')->find($linkId);工作正常。

答案 1 :(得分:-1)

$ data = Link :: with('owner')-> find($ linkId)-> get();

相关问题