查询所有列表ID包含用户ID的地方 [英] Query all where list id has user id

查看:115
本文介绍了查询所有列表ID包含用户ID的地方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在监视列表中获取所有属性,其中该监视列表具有用户ID.

I'm trying to get all the properties, in a watchlist(s) where the list has a user id.

关系设置如下.

每个监视列表与一个用户ID相关.每个媒体资源都有一个监视列表ID.

Each watchlist is related to a user id. Each Property has a watchlist id.

我需要属于该用户的所有监视列表中的所有属性.

I need all properties, in all the watchlists belonging to that user.

监视列表在创建后自动获得user_id.

The watchlist gets the user_id automatically upon creation.

这是我的模特

监视列表

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

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

WatchedProperties

WatchedProperties

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

查询 获取每个列表中的所有图书,而无需考虑用户ID和列表ID

Query Gets all books in every list disregarding user ids and list ids

$Watchlists = WatchedBooks::all();

当前获取所有书籍,无论用户ID是什么.

Currently gets all books regardless of userid.

我需要所有用户列表中的所有图书.

I need all books in all of the user's lists.

一个用户可以有多个列表 清单A 清单B

A user could have multiple lists List A List B

类似 列表ID与用户ID相关的所有列表中的所有图书.

So something like All books from all lists where the list id is related to user id.

这是监视列表数据库的外观 监视列表

This is what the Watchlist DB looks like WatchlistDB

这是WatchedBooks数据库的外观 监视列表中的书

This is what the WatchedBooks DB looks like Books in watchlist

推荐答案

Laravel为此提供了一个漂亮的解决方案:您可以向用户模型添加->hasManyThrough关系.您可以在有关口才关系的Laravel文档.

Laravel has a beautiful solution for this: you can add a ->hasManyThrough relation to the user model. You can find more information about this type of relation in the Laravel documentation about Eloquent relationships.

用户模型如下所示:

class User extends Model {

    [...]

    public function watchedBooks()
        return $this->hasManyThrough('App\WatchedBook', 'App\Watchlist');
    }

    [...]

}

然后,您可以使用

$user->watchedBooks;

$user->watchedBooks()->yourBuilderQueryHere()->get();

这篇关于查询所有列表ID包含用户ID的地方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆