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 사용되고 있으며 그 방법은 다음과 같습니다 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';
}