Eloquent:嵌套关系返回null

时间:2016-09-29 22:11:10

标签: join nested eloquent

问题 我想获得有关campagin的信息,以及所有角色的一部分。但我也想要角色肖像。当我尝试这样做时,我会得到信息和字符,但不是肖像。

广告系列模型

spacing = cumsum([1; e(:,2)]);      % the rows of new_e where we change row values
row_indices(spacing) = 1;           % make a vector with these elements = 1
row_indices = cumsum(row_indices);  % convert to row indices, last index is invalid
new_e = e(row_indices(1:end-1), :); % select valid rows from e

角色模型

public function player_characters()
{
        return $this->hasMany('Sagohamnen\Character\Character', 'campaign_id')->select('id','campaign_id', 'name', 'portrait_id')->where('characters.type', 1)->where('characters.status', 1);
}

Eloquent查询

public function thumb_portrait()
{
    return $this->belongsTo('Sagohamnen\Portrait\Portrait')->select('thumbnail', 'id');
}

结果

return Campaign::select('id', 'genre', 'name', 'description',
'max_nr_players', 'rating', 'created_at', 'updated_at')->where('id',
$campaign_id)->with('player_characters.thumb_portrait')->first();

字符数据库表

string(139) "select `id`, `genre`, `name`, `description`, `max_nr_players`, `rating`, `created_at`, `updated_at` from `campaigns` where `id` = ? limit 1"
array(1) {
  [0]=>
  string(1) "1"
}
string(165) "select `id`, `campaign_id`, `name`, `portrait_id` from `characters` where `characters`.`type` = ? and `characters`.`status` = ? and `characters`.`campaign_id` in (?)"
array(3) {
  [0]=>
  int(1)
  [1]=>
  int(1)
  [2]=>
  int(1)
}
string(71) "select `thumbnail`, `id` from `portraits` where `portraits`.`id` in (?)"
array(1) {
  [0]=>
  int(0)
}

人像DB表

id - name - portrait_id
1    Gandalf  3

1 个答案:

答案 0 :(得分:1)

当我将关系方法“thumb_portrait”更改为“portrait”时,将显示纵向数据。显然,关系方法应该与外键具有相同的名称(除非我将自定义外键作为第二个参数传递)。

根据有关oneToMany逆转的文档:

  

Eloquent通过检查名称来确定默认外键名称   关系方法和后缀方法名称与_id。