【发布时间】:2019-01-30 08:11:09
【问题描述】:
我试图在执行与用户相关的操作之前确保数据库中存在一条记录。当我像这样直接在我的 PHPMyAdmin 中执行查询时(出于测试目的)。
SELECT * FROM `chat_participants` WHERE `chat_id` = 2 AND `user_id` = 2
我收到了正确的记录。但是,当我尝试使用 Laravel Query Builder 来实现相同的目标时。
dd($this->participants
->where('chat_id', '=', 2)
->where('user_id', '=', 2)
->get()
->first());
我得到null. 有没有办法可以使用查询生成器确保记录存在于数据库中?我需要在查询生成器中声明AND 吗?
更新:我在构造函数中设置了 participants 变量。
public function __construct()
{
$this->middleware('auth');
$this->header = DB::table('chat_headers');
$this->participants = DB::table('chat_participants');
$this->messages = DB::table('chat_messages');
}
toSql() 产生:
select * from chat_participants`
inner join chat_headers on chat_headers.id = chat_participants.chat_id
inner join chat_rbac on chat_rbac.id = chat_participants.rbac
where chat_participants.chat_id = ? and chat_participants.user_id = ?
and chat_id = ? and user_id = ?
【问题讨论】:
-
这里的
participants属性是什么? -
更新问题以显示@Devon
-
执行
$this->participants->where('chat_id', '=', 2)->where('user_id', '=', 2)->toSql()以查看正在生成的 SQL 查询。多个where()呼叫会自动AND一起使用。旁注:->get()->first()可以是->first()。 -
->get()->first()是多余的顺便说一句;->get()将返回与您的查询匹配的记录的Collection,然后->first()将返回这些记录中的第一个。您可以简单地使用->first()来节省一些计算时间。 -
"select * fromchat_participants` 内连接chat_headersonchat_headers.id=chat_participants.chat_id内连接chat_rbacon @9876543446@.@98676 @.rbacchat_participants.chat_id= ?和chat_participants.user_id= ?和chat_id= ?和user_id= ?` @ceejayoz
标签: php laravel laravel-5 laravel-query-builder