search

Home  >  Q&A  >  body text

Looking for one-to-one and one-to-many native query statements in Laravel

Route::get('test', function () {

DB::connection()->enableQueryLog();

// Get the executed query array

Users::with('posts')->get();
dd(DB::getQueryLog());

});

array:2 [▼
0 => array:3 [▼

"query" => "select * from `users`"
"bindings" => []
"time" => 2.76

]
1 => array:3 [▼

"query" => "select * from `posts` where `posts`.`users_id` in (?, ?)"
"bindings" => array:2 [▶]
"time" => 0.71

]
]

In the above code, why not select id from user and then use this query result in the next step?

仅有的幸福仅有的幸福2809 days ago349

reply all(1)I'll reply

  • 淡淡烟草味

    淡淡烟草味2017-05-16 16:48:54

    `select * from users` 可以获得users的所有数据
    `select * from `posts` where `posts`.`users_id` in (?, ?)` 
    可以把上一条语句的id放入in()获得posts表里users_id匹配的数据,接下来就可以用php来拼接数据,这样只要两条sql。
    如果用select * from `posts` where `posts`.`users_id` in(select id from user)那么使用了自查询不说,而且users表的字段要怎么查询?
    以上,个人理解,欢迎打脸!

    reply
    0
  • Cancelreply