简单的laravel一对多关系 - 从两个表中获得结果

har*_*ryg 1 php laravel eloquent laravel-4

所以我有一个客户端模型和一个风险类别模型.关系如下所示,表格遵循常规约定:

//Client.php
public function riskCategory()
{
    return $this->belongsTo('RiskCategory');
}

//RiskCategory.php
public function clients()
{
    return $this->hasMany('Client');
}
Run Code Online (Sandbox Code Playgroud)

我想通过id查询客户端,同时获取风险类别数据.

如果我使用Client::find($id);我获取clients表中所有字段的ID,如果我这样做,Client::find($id)->riskcategory;我只得到风险类别表的字段.

有没有办法一次从两个表中获取字段?即如果我使用Id 175查询客户端,我会在同一查询中获得该客户端的所有客户端字段(名称,年龄,地址等)和风险类别?

Sve*_*len 6

您可以通过多种方式将风险类别中的数据添加到用户.取决于您想要如何使用它.

将客户端数据用作数组:

// get the client with ID 2 and eager load the riskcategory relation.
$client_data = Client::with('riskcategory')->find(2)->toArray();
Run Code Online (Sandbox Code Playgroud)

使用客户端数据作为Eloquent:

// get the client with ID 2 and eager load the riskcategory relation.
$client = Client::with('riskcategory')->find(2);
Run Code Online (Sandbox Code Playgroud)

有关预先加载的更多信息:渴望加载信息