脚本宝典收集整理的这篇文章主要介绍了php – 在返回的数据库对象上运行字符串函数的最佳方法,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
现在也许有一个很好的方法在我的模型上设置Accessors并以某种方式在着陆页上使用该模型,但我想我会走另一条路线,只是在模型之外手动执行这一个查询.
所以我有一个视图提供程序,可以成功地将我的数据导入视图.它看起来像这样:
class ViewLandingPRovider extends ServiceProvider { public function boot() { // process when featured homepage element is present... View::composer('mybladetemplate',function ($view){ $featuredProPErties = DB::table('properties') ->where([ ['featured_property','=','1'],['supplier_id',123],]) ->orderBy('prop_id','desc') ->limIT(6) ->get(); // run str_replace! $featuredProperties->each(function($property){ $property->prop_url=str_replace("http://domain.COM/","http://www.domain.com/",$property->prop_url); }); View::share('featuredProperties',$featuredProperties); }); } }
然后它在一个视图中循环,一切都很好
@if(isset($featuredProperties)) @foreach ($featuredProperties as $property) <li> <a title="{{ $property->prop_name }}" href="{{ $property->prop_url }}"></a> </li> @enDForeach @endif
正如您在上面的示例中所看到的,我使用 – > each()在数据集合上运行str_replace(),并且我正在努力让我做一个我需要进行的简单字符串替换.
虽然是Laravel,但我确信有一些魔法可以被拉到这里以更聪明地做到这一点.
Collection::macro('formatPropUrl',function() { return collect($this->items)->map(function($property) { $property->prop_url=str_replace("http://domain.com/",$property->prop_url); return $property; }); });
然后,您可以执行以下操作:
$featuredProperties = DB::table('properties') ->where([ ['featured_property',]) ->orderBy('prop_id','desc') ->limit(6) ->get() ->formatPropUrl();
以上是脚本宝典为你收集整理的php – 在返回的数据库对象上运行字符串函数的最佳方法全部内容,希望文章能够帮你解决php – 在返回的数据库对象上运行字符串函数的最佳方法所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。