Laravel 查询生成器在数据库中明确存在时返回 NULL 结果
Laravel query builder returning NULL results when they are clearly in the DB
查询:
$posts = $this->post->with('games', 'console')->take($limit)->get();
所以实际上丢弃了 $post 我在第 4 个条目中看到了这个...它是 returning NULL
["relations":protected]=>
array(2) {
["games"]=>
NULL
前 3 个 return 值。但是第四个都是 returning NULL。同样,我在游戏中只有 3 个值 table
Games Table:
1 | game 1
2 | game 2
3 | game 3
实际上在第三个条目上它的值为 2 但显示游戏 3 名称
posts table:
id | game id
1 | 3
2 | 2
3 | 3 (but showing "game 1" text)
4 | 3 (anything from 4 on returns NULL)
关系:
Game
public function Post()
{
return $this->hasMany('App\Post', 'game_id');
}
Post
public function console()
{
return $this->belongsTo('App\Console', 'id');
}
public function games()
{
return $this->belongsTo('App\Game', 'id');
}
Console
public function Post()
{
return $this->hasMany('App\Post', 'console_id');
}
试试这个:
Post
public function games()
{
return $this->hasOne('App\Game', 'id', 'game_id');
}
在您的 Post
class 中,您使用的关系 games
错误。
首先,它应该被称为game
单数,因为Post
只属于一个Game
。但是,它可以使用复数形式。
那么,真正的问题是你是这样声明关系的:
public function games()
{
return $this->belongsTo('App\Game', 'id');
}
这告诉 Laravel Post
与列 id
的游戏相关,因此例如,记录:{id : 1, game_id : 3}
将与Game
与 id
1,它应该与 id 3 的 Game
相关。 belongsTo
方法的第二个参数是本地列。第三个参数是父列上的 id
。但默认情况下它是 id
,所以你不应该使用它们中的任何一个。
public function games()
{
return $this->belongsTo('App\Game');
}
你在console
中遇到了同样的问题
希望对您有所帮助。
查询:
$posts = $this->post->with('games', 'console')->take($limit)->get();
所以实际上丢弃了 $post 我在第 4 个条目中看到了这个...它是 returning NULL
["relations":protected]=>
array(2) {
["games"]=>
NULL
前 3 个 return 值。但是第四个都是 returning NULL。同样,我在游戏中只有 3 个值 table
Games Table:
1 | game 1
2 | game 2
3 | game 3
实际上在第三个条目上它的值为 2 但显示游戏 3 名称
posts table:
id | game id
1 | 3
2 | 2
3 | 3 (but showing "game 1" text)
4 | 3 (anything from 4 on returns NULL)
关系:
Game
public function Post()
{
return $this->hasMany('App\Post', 'game_id');
}
Post
public function console()
{
return $this->belongsTo('App\Console', 'id');
}
public function games()
{
return $this->belongsTo('App\Game', 'id');
}
Console
public function Post()
{
return $this->hasMany('App\Post', 'console_id');
}
试试这个:
Post
public function games()
{
return $this->hasOne('App\Game', 'id', 'game_id');
}
在您的 Post
class 中,您使用的关系 games
错误。
首先,它应该被称为game
单数,因为Post
只属于一个Game
。但是,它可以使用复数形式。
那么,真正的问题是你是这样声明关系的:
public function games()
{
return $this->belongsTo('App\Game', 'id');
}
这告诉 Laravel Post
与列 id
的游戏相关,因此例如,记录:{id : 1, game_id : 3}
将与Game
与 id
1,它应该与 id 3 的 Game
相关。 belongsTo
方法的第二个参数是本地列。第三个参数是父列上的 id
。但默认情况下它是 id
,所以你不应该使用它们中的任何一个。
public function games()
{
return $this->belongsTo('App\Game');
}
你在console
希望对您有所帮助。