我正在尝试使用Eloquent为Laravel中的帖子构建一个简单的新闻源.
我基本上想要检索所有帖子……
>我是作者
>我关注的人是作者(可跟随)
>我关注的人对此进行了评论
>具有相同field_id的人是作者
>具有相同school_id的人是作者
在一个查询中.
因为我从未对加入/组合的SQL查询进行过强烈的工作,所以对此的任何帮助都非常感谢!
我的桌子
用户表
+----+
| id |
+----+
帖子表
+----+-----------+-------------+
| id | author_id | author_type |
|----|-----------|-------------|
| | users.id | 'App\User' |
+----+-----------+-------------+
评论表
+----+----------------+------------------+-----------+-------------+
| id | commentable_id | commentable_type | author_id | author_type |
|----|----------------|------------------|-----------|-------------|
| | posts.id | 'App\Post' | users.id | 'App\User' |
+----+----------------+------------------+-----------+-------------+
学者桌
+---------+-----------+----------+
| user_id | school_id | field_id |
+---------+-----------+----------+
跟随表
+-------------+---------------+---------------+-----------------+
| follower_id | follower_type | followable_id | followable_type |
|-------------|---------------|---------------|-----------------|
| users.id | 'App\User' | users.id | 'App\User' |
+-------------+---------------+---------------+-----------------+
我的模特
class Post extends Model
{
/**
* @return \Illuminate\Database\Eloquent\Relations\MorphTo
*/
public function author()
{
return $this->morphTo();
}
/**
* @return \Illuminate\Database\Eloquent\Relations\MorphMany
*/
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}
class Comment extends Model
{
/**
* @return \Illuminate\Database\Eloquent\Relations\MorphTo
*/
public function author()
{
return $this->morphTo();
}
/**
* @return \Illuminate\Database\Eloquent\Relations\MorphTo
*/
public function commentable()
{
return $this->morphTo();
}
}
class User extends Model
{
/**
* @return \Illuminate\Database\Eloquent\Relations\MorphMany
*/
public function posts()
{
return $this->morphMany(Post::class, 'author')->orderBy('created_at', 'desc');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\MorphMany
*/
public function comments()
{
return $this->morphMany(Comment::class, 'author')->orderBy('created_at', 'desc');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function schoolables()
{
return $this->hasMany(Schoolable::class);
}
/**
* @return \Illuminate\Database\Eloquent\Relations\MorphMany
*/
public function following()
{
return $this->morphMany(Followable::class, 'follower');
}
}
最佳答案 您可以尝试对此查询使用左连接,但它会变得很复杂,因为您必须使用leftJoins进行所有连接,然后对所有连接进行嵌套的orWhere子句
$posts = Post::leftJoin('..', '..', '=', '..')
->where(function($query){
$query->where('author_id', Auth::user()->id); // being the author
})->orWhere(function($query){
// second clause...
})->orWhere(function($query){
// third clause...
.....
})->get();
我不认为这是可以管理的,所以我建议使用UNIONS,http://laravel.com/docs/5.1/queries#unions
所以它会像..
$written = Auth::user()->posts();
$following = Auth::user()->following()->posts();
获得不同的查询后,无需获得结果,您可以将它们联合起来..
$posts = $written->union($following)->get();
希望这会引导您朝着正确的方向前进