質問

コードを持っています:

$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';
}
.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top