Php 限制Laravel中的重复查询
我只需要查询中最新的5行,因此我使用Php 限制Laravel中的重复查询,php,mysql,laravel,Php,Mysql,Laravel,我只需要查询中最新的5行,因此我使用 $view->with('recent', Transaction::SELECT('amount') ->latest() ->where('amount', '!=', null) ->take(5)->get()); 这为我提供了视图中所需的内容,但调试栏显示: 14 statements were executed, 14 of which were duplicated 我目前在该表中有14条记录。我在表中添加的记
$view->with('recent', Transaction::SELECT('amount')
->latest()
->where('amount', '!=', null)
->take(5)->get());
这为我提供了视图中所需的内容,但调试栏显示:
14 statements were executed, 14 of which were duplicated
我目前在该表中有14条记录。我在表中添加的记录越多,得到的重复项就越多
我怎样才能减少这些疑问
现在这样称呼它:
@foreach($recent as $rec)
<li>{{ number_format($rec->amount / 100, 2) }}</li>
@endforeach
@foreach($rec)
{{number_格式($rec->amount/100,2)}
@endforeach
试试这个
将“change.to.footer”更改为footer.blade.php路径
将\App\Transaction更改为您的模型路径
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
view()->composer('change.to.footer', function ($view) {
$view->with('recent', \App\Transaction::SELECT('amount')
->latest()
->where('amount', '!=', null)
->take(5)->get());
});
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
如果要在所有刀片中使用该变量
也许你可以做一个模型的方法
// Transaction model
public static function recent()
{
return static::SELECT('amount')
->latest()
->where('amount', '!=', null)
->take(5)->get());
}
创建视图生成器
public function boot()
{
view()->share('recent', \App\Transaction::recent());
}
您是否能够将
->get()
替换为->toSql()
,以查看正在生成的查询?另外,->where('amount','!=',null)
应该是->where notnull('amount')
我相信。在我的DD上,我用->toSql
得到最近的“=>”从交易中选择金额
不是由创建的空订单
描述限额5“`似乎您正在将代码块放入loop@kenken9999我叫它这个。请参阅有问题的更新。您将代码$view->with………,放在哪里,它看起来像view composer?我花了一分钟的时间对它进行了思考,但在我禁用了view composer逻辑后,它起到了很大的作用。现在只使用了一个查询。非常感谢。快速提问,而不是使用ViewComposer方法。我可以简单地将全局查询添加到AppServiceProvider吗?如果您想要一个可以在所有刀片服务器上使用的变量,可以使用view()->share('recent',$get_what_you_)