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
(PHPデータオブジェクト)の通常の動作です。 PDO
のようなPDO
という名前のparameter/placeholder
が:totle
の代わりに使用される別の方法があります。与えられたリンクでそれについてもっと読むと、もう一つのトピックです。 この回答。< / P>
更新:実行時に?
マークが指定した値に置き換えられるので、?
は?
に置き換えられます。また、この1
はリレーショナルクエリです。すべてのクエリログを表示するには、代わりにこれを試してください。
$queries = \DB::getQueryLog();
dd($queries);
.
次のコールのクエリをデバッグするには、最後の2つのクエリを確認できます。
$response = $this->posts
->where('author_id', '=', 1)
->with(array('postComments' => function($query) {
$query->where('comment_type', '=', 1);
}))
->orderBy('created_at', 'DESC')
->limit($itemno)
->get();
.
清澄化後の更新:
query
モデルで設定関係がある場合は、このようなものを使用できます。
// $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();
.
id
の関係を宣言する必要があります(可能であれば、特異な名前posts
を使用してください)モデル:
public function comments()
{
return $this->hasmany('Comment');
}
.
あなたのPosts
モデルは次のようにする必要があります:
class Comment extends Eloquent {
protected $table = 'post_comments';
}
. 所属していません StackOverflow