我已经拥有的和我正在尝试做的:
我有一个网站,允许用户发帖向其他用户宣传自己。现在,我正在尝试为这些帖子实现一个过滤器,但要按用户表、帖子表和其他三个表中的值进行过滤。这就是我遇到麻烦的地方。
按原样运行的代码,没有过滤器:
$posts = Post::with('user','lookingfors','playstyles', 'postcomments')->orderBy('id', 'DESC')->paginate(10);
return View::make('posts/index', compact('posts'));
这是我试过的:
$posts = User::leftjoin('posts', function($join)use($region){
$join->on('users.id', '=', 'posts.user_id');
$join->on('playstyle_post.post_id', '=', 'posts.id'); // join pivot, then join pivot to playstyles
$join->on('playstyle_post.playstyle_id', '=', 'playstyles.id');
//$join->on;
})->where('users.region_id', 'like', $region)->get();
这个一直报错:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'playstyle_post.post_id' in 'on clause' (SQL: select * from
users
left joinposts
onusers
.id
=posts
.user_id
andplaystyle_post
.post_id
=posts
.id
andplaystyle_post
.playstyle_id
=playstyles
.id
whereusers
.region_id
like ?) (Bindings: array ( 0 => 6, ))
还有:
$posts = Post::with('lookingfors', 'playstyles', 'postcomments')
->leftjoin('users', 'posts.user_id', '=', 'users.id')
//->join('playstyle_post', 'posts.id', '=', 'playstyle_post.post_id')
->paginate(10);
这个很奇怪(对我来说很好),当“leftjoin”被注释掉时,它显然和以前一样工作,但是当我现在拥有它时,它会显示它应该显示的 View ,甚至提取所有正确的值来自用户表,但不显示通过“with”请求的任何信息。
在过去的两周里我尝试了一些其他的东西,但当它们不起作用时我已经把它们扔掉了。半个月以来,这一直困扰着我,我无法理解为什么我无法让它工作。
所以说真的,我现在的麻烦只是试图连接表并以一种 Eloquent 方式将其返回到 View ,这样我就可以继续以同样的方式对待它。过滤器本身将是一个问题,但事实证明让连接正常工作是困难的部分。
最佳答案
与其将一堆关系名称传递给 with()
函数,不如尝试传递一个数组,将键设置为关系的名称,将值设置为回调函数,并传入查询实际编辑。还必须在需要时使用 use ($region)
。希望你明白了。
我举了一些例子来为每个关系添加过滤器。因为您是在本地处理每一个,所以您不必担心为它们添加表名或别名前缀。
$posts = Post::with(array(
'user' => function($query) use ($region)
{
// User constraints here
$query->where('status', 'A');
$query->where('deleted', '0');
},
'lookingfors' => function($query)
{
// lookingfors constraints here
$query->where('name', 'somelookingforname');
},
'playstyles' => function($query)
{
// playstles constraints here
$query->where('name', 'someplaystylesname');
},
'postcomments' => function($query)
{
// Some postcomments constraints here
$query->where('name', 'somepostcommentsname');
}))
->orderBy('id', 'DESC')
->paginate(10);
不过,看看您对左连接的尝试,我不知道这些关系是否正确。我的示例假设所有关系都可以直接关联回用户表。否则,您将需要更改数组中的键以匹配应有的关系。
例如,如果尝试关联playstyles
表,但playstyles
和posts
之间的关系不存在,因为您需要要首先查看 users
表,您只需将 'playstyles'
更改为 'users.playstyles'
。
如果您发布迁移,我可以进一步帮助您。
关于sql - 在 laravel [实现过滤器] 中通过 Eloquent 和急切的加载将多个表连接在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21632416/