Laravel 口才与关系
-
20-12-2019 - |
题
我有一个代码:
$response = $this->posts
->where('author_id', '=', 1)
->with(array('postComments' => function($query) {
$query->where('comment_type', '=', 1);
}))
->orderBy('created_at', 'DESC')
->limit($itemno)
->get();
当我用以下命令记录此查询时:
$queries = \DB::getQueryLog();
$last_query = end($queries);
\Log::info($last_query);
在日志文件中我看到以下内容:
"select * from `post_comments` where `post_comments`.`post_id` in (?, ?, ?, ?) and `comment_type` <> ?"
为什么查询中的 comment_type 是问号?
更新#1:
我用以下代码替换了当前代码,得到了我想要的。但我不确定是否可以。也许存在许多更好、更好的解决方案。
$response = $this->posts
->where('author_id', '=', 1)
->join('post_comments', 'post_comments.post_id', '=', 'posts.id')
->where('comment_type', '=', 1)
->orderBy('created_at', 'DESC')
->limit($itemno)
->get();
解决方案
幕后的 磷酸二氢钾 正在被使用,就是这样 PDO
作为准备好的查询,例如检查以下内容:
$title = 'Laravel%';
$author = 'John%';
$sql = "SELECT * FROM books WHERE title like ? AND author like ? ";
$q = $conn->prepare($sql);
$q->execute(array($title,$author));
在运行时执行查询期间 execute()
这 ?
标记将被传递的值替换 execute(array(...))
. Laravel/Eloquent
用途 PDO
这是正常行为 PDO
(PHP 数据对象)。还有另一种方法用于 PDO
, ,它被命名为 parameter/placeholder
喜欢 :totle
被用来代替 ?
. 。在给定的链接中阅读更多相关信息,这是另一个主题。另请检查 这个答案.
更新: 在运行时 ?
标记将替换为您提供的值,因此 ?
将被替换为 1
. 。还有这个 query
是关系查询,第一个查询完成加载后的第二部分 id
是从 posts
桌子。要查看所有查询日志,请尝试以下操作:
$queries = \DB::getQueryLog();
dd($queries);
您可以检查最后两个查询来调试以下调用的查询:
$response = $this->posts
->where('author_id', '=', 1)
->with(array('postComments' => function($query) {
$query->where('comment_type', '=', 1);
}))
->orderBy('created_at', 'DESC')
->limit($itemno)
->get();
澄清后更新:
如果您的设置中有设置关系,则可以使用类似的东西 Posts
模型:
// $this->posts->with(...) is similar to Posts::with(...)
// if you are calling it directly without repository class
$this->posts->with(array('comments' =. function($q) {
$q->where('comment_type', 1);
}))
->orderBy('created_at', 'DESC')->limit($itemno)->get();
为了使其正常工作,您需要在您的 Posts
(尽量使用单数名称 Post
如果可能的话)型号:
public function comments()
{
return $this->hasmany('Comment');
}
你的 Comment
模型应该是这样的:
class Comment extends Eloquent {
protected $table = 'post_comments';
}
不隶属于 StackOverflow