坑:
1.relationship分页问题
laravel的relationship分页,在使用动态属性时,分页错误。代码稍后提供。
2.门面的多连接问题
如果db有多个连接时,想当然的写法是mydb.mytable, 但是在门面模式下,laravel会用默认的连接(例如:defaultdb)而不是你认为的mydb。
错误信息:
SQLSTATE[42000]: Syntax error or access violation: 1142 SELECT command denied
to user 'xxxxx'@'xx.xx.xx.xx' for table 'sale_area'
/*
错误写法
*/
$orm = DB::table('mydb.sale_area')
->leftJoin('mydb.sale_group_relation', 'mydb.sale_area.id', '=', 'mydb.sale_group_relation.child_id');
/*
正确写法:
指定connection,并强制read模式
*/
$orm = DB::connection("mydb::read")->table("sale_area")
->leftJoin('sale_group_relation', 'sale_area.id', '=', 'sale_group_relation.child_id');
$orm->where('sale_area.id', $condition['id']);
$orm->select(['*']);
return $orm->get()->toArray();
调试技巧
监听database的事件(StatementPrepared, ConnectionEvent, QueryExecuted), 并通过Log::info输出.
监听代码:
class EventServiceProvider extends ServiceProvider {
public function boot() {
parent::boot();
// 监听事务时触发
Event::listen(ConnectionEvent::class, function ($event){
Log::info(ConnectionEvent::class, $event->connection->getConfig());
});
// 监听日志记录的db操作
Event::listen(QueryExecuted::class, function ($event){
Log::info(QueryExecuted::class,
[
'connection'=>$event->connection->getConfig(),
'sql' => $event->sql,
'time' => $event->time,
'bindings' => $event->bindings,
]);
});
// 监听PdoStatement操作
Event::listen(StatementPrepared::class, function ($event) {
ob_start();
$event->statement->debugDumpParams();
$dump = ob_get_clean();
Log::info(StatementPrepared::class,
[
'connection'=>$event->connection->getConfig(),
'debugDumpParams' => $dump,
'errorCode' => $event->statement->errorCode(),
'errorInfo' => $event->statement->errorInfo(),
'queryString' => $event->statement->queryString,
]);
});
}
}