问题描述
我正在尝试在监视列表中获取所有属性,其中该监视列表具有用户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
QueryGets 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 listsList AList B
类似列表ID与用户ID相关的所有列表中的所有图书.
So something likeAll books from all lists where the list id is related to user id.
这是监视列表数据库的外观监视列表
This is what the Watchlist DB looks likeWatchlistDB
这是WatchedBooks数据库的外观监视列表中的书
This is what the WatchedBooks DB looks likeBooks 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的地方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!