php - 通过 laravel 运行时返回 null 的工作查询

标签 php mysql laravel

我正在尝试对 laravel 使用一个简单的查询,但它没有返回任何数据。但是当我在 phpmyadmin 中运行相同的查询时,它返回 3 行。

这是 laravel 中的代码。

 $pages = DB::table('static_pages')
     ->where('slug','=','(select slug from static_pages where id='.$id.')')
         ->get();

这是它进行的查询。

  select * from `static_pages` where `slug` = (select slug from static_pages where id=2)

你能告诉我可能是什么原因吗?

最佳答案

如果您指的是两个表之间的关系,那么您可能想要查看 Laravel 模型关系,但是如果您想要检索具有相同 slug of 记录的所有记录使用 id = 2 那么你也可以不使用两个 DB:raw:

DB::table('static_pages')->where('slug', function ($query) {
        return $query->from('static_pages')->where( 'id', '2')->select('slug');
    })->get();

如果您想检查它生成的 sql 查询,请使用 toSql() 而不是 ->get()

要预料到的一件坏事是,如果您的内部查询返回一组值,那么您的比较可能会变得有问题。但是,由于您用来进行查询的字段是唯一的,因此这应该不是问题。

希望这是有用的。

关于php - 通过 laravel 运行时返回 null 的工作查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46343167/

相关文章:

mysql - 将换行符转换为空格 MYSQL

php - 如何在 Laravel 6 中删除数据库?

php - CodeIgniter:如果我使用 die() 函数,则不会加载 View

php - 登录时重定向到不同页面 - php

php - 聊天和数据结构集成

php - 使用 Twig 进行模板化 - 永久访问我所有模板中的变量

php - mysql OR 子句对应于 AND 子句

mysql - nodejs mysql多个where查询

laravel - VueJS 和 laravel 验证数组

php - Laravel 5.2 artisan 优化 - php_strip_whitespace 无法打开流 : No child processes