【问题标题】:How to access only the related model with eager loading如何通过急切加载仅访问相关模型
【发布时间】:2017-12-06 05:22:14
【问题描述】:

我的项目中有这些模型:

class User {

    public function favorites()
    {
        return $this->hasMany('App\Favorite');
    }

}

-

class Product {

    public function user()
    {
        return $this->belongsTo('App\User');
    }

}

-

class Favorite {

    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function product()
    {
        return $this->belongsTo('App\Product');
    }

}


当我尝试获取用户的收藏时,我会这样做:-

$user = User::find(1);
return $user->favorites;

或者用他最喜欢的产品:-

return $user->favorites->load('product');

但它会同时返回(产品和收藏夹)的结果。

如何通过收藏只从产品模型中获取结果?

比如我只想检索用户添加到收藏夹中的产品?

我已经尝试在 User 类中进行此操作,但它不起作用:-

public function favproducts()
{
    return this->hasManyThrough('App\Product', 'App\Favorite');
}


提前谢谢你。

【问题讨论】:

  • 你想通过雄辩来做吗,因为你可以通过查询来做。
  • 是的,我知道我可以使用连接和类似的东西来做到这一点,但我更喜欢以雄辩的方式来做到这一点。
  • 你可以试试$user->favorites()->with('product')->get()
  • 这和 $user->favorites->load('product'); 完全一样这将为我返回两个模型,我只需要没有收藏夹模型的产品
  • 这应该只是它们之间的数据透视表吗?并且您没有在 Product 上定义 favorites 关系。无法在您的设置中从产品转到收藏夹,这就是如何获得您想要的东西。

标签: php laravel orm eloquent


【解决方案1】:

这似乎可以是UserProduct 之间的belongsToMany,以创建“收藏夹”,作为数据透视表。

您当前的设置缺少从 ProductFavorite 的反向关系,因此您不能在该方向上使用该关系。我将使用哪个方向来获得您想要的结果。

如果您设置了关系,您可能会这样做以获取用户最喜欢的产品。

Product::whereHas('favorites.user', function ($q) use ($user_id) {
    $q->where('id', $user_id);
})->get();

使用id == $user_id 获取用户喜爱的所有产品。

如果这是为 belongsToMany 设置的,您可能只是这样做:

User::find($id)->favorites;

使用您当前拥有的内容,您可以从 PHP 端的结果中“获取”子记录。

【讨论】:

    【解决方案2】:

    试试这个: 在你的情况下,我认为这是一个嵌套的渴望加载

    $user = User::with('favorites.product')->get();
    //to grab the data
    dd($user->favorites[0]->product);
    

    希望对你有帮助

    【讨论】:

      【解决方案3】:

      试试:

      $user->favorites->product['name']
      

      【讨论】:

      • 试图访问 Collection 的 product 属性
      猜你喜欢
      • 1970-01-01
      • 2022-12-19
      • 2013-06-10
      • 1970-01-01
      • 1970-01-01
      • 2014-09-08
      • 2016-05-28
      • 2014-05-21
      • 1970-01-01
      相关资源
      最近更新 更多