【问题标题】:Laravel Eloquent relationship only returns minimal resultsLaravel Eloquent 关系只返回最小的结果
【发布时间】:2016-05-14 17:14:43
【问题描述】:

表格:

Posts
id | console_id | game_id | etc

Games
id | name

Console
id | name

现在,当我查询此关系时,我不断收到“尝试获取非对象的属性”错误。现在,如果我将结果限制为前 3 名(这是我在游戏表中所拥有的全部),那么它将运行,但除此之外它会抛出异常......关系错了吗?

关系:

Game
public function Post()
{
    return $this->belongsTo('App\Post', 'game_id');
}

Post
public function console()
{
    return $this->hasOne('App\Console', 'id');
}

public function games()
{
    return $this->hasOne('App\Game', 'id');
}

Console
public function Post()
{
    return $this->belongsTo('App\Post', 'console_id');
}

更新

@joel @rashmi 所以实际上倾销了 $post 我在第 4 个条目上看到了这个......它返回 NULL

["relations":protected]=>
  array(2) {
    ["games"]=>
    NULL

前 3 个返回值。但随后第 4 次都返回 NULL。同样,我在 Games 表中只有 3 个值

Games Table:
1 | game 1
2 | game 2
3 | game 3

实际上在第三个条目上它的值为 2 但显示游戏 3 名称

posts table: 
id | game id
1 | 2
2 | 3
3 | 2 (but showing "game 1" text)

【问题讨论】:

    标签: laravel eloquent lumen


    【解决方案1】:

    看起来您的帖子都属于游戏机和游戏 - 而不是相反。 hasOne 表示只能有一个,但每个控制台和游戏都可以有很多帖子。所以应该是这样的:

    // Game
    public function posts()
    {
        return $this->hasMany('App\Post');
    }
    
    // Post
    public function console()
    {
        return $this->belongsTo('App\Console');
    }
    
    public function game()
    {
        return $this->belongsTo('App\Game');
    }
    
    // Console
    public function posts()
    {
        return $this->hasMany('App\Post');
    }
    

    如果您的表格分别命名为控制台、游戏和帖子,那么您不需要提供 ID,因此我将它们删除。如果需要,您可以重新添加它们。

    【讨论】:

    • 是的,只是添加了特定名称以避免任何其他问题。所以我进行了切换,现在在我的 postTransformer 中遇到“尝试获取非对象的属性”:'game' => $post->games->name,虽然返回的对象是 Games...
    【解决方案2】:

    看来你们的关系不太好。应该是这样的:

    // Game Model
    public function posts()
    {
       return $this->hasMany('App\Post');
    }
    
    // Post Model
    public function console()
    {
       return $this->belongsTo('App\Console');
    }
    
    public function game()
    {
       return $this->belongsTo('App\Game');
    }
    
    // Console Model
    public function posts()
    {
       return $this->hasMany('App\Post');
    }
    

    您对帖子的雄辩查询将是:

    $this->model->select(SELECTED_FIELDS)
                ->with(array('game','console'))
                ->get();
    

    其中 SELECTED_FIELDS 表示您要获取的表字段。

    【讨论】:

    • 所以我进行了切换,现在在我的 postTransformer: 'game' => $post->games->name 中遇到“尝试获取非对象的属性”,返回的对象是游戏虽然...
    猜你喜欢
    • 2021-01-26
    • 1970-01-01
    • 2020-05-01
    • 2015-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-22
    • 2021-11-06
    相关资源
    最近更新 更多