在使用Laravel 5.3将其发送到 View 之前,我需要对数据库返回的数据运行各种字符串函数。基本的东西,例如str_replace()。

现在,也许有一种在我的模型上设置访问器并以某种方式在登录页面上使用该模型的好方法,但是我想我会走另一条路线,只是在模型外部手动执行此查询。

因此,我有一个 View 提供程序,可以将我的数据成功获取到 View 中。看起来像这样:

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);
    });
  }
}

然后在 View 内循环,一切都很好
 @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,我敢肯定,这里可以运用一些魔术来更智能地完成此操作。

那么,在实际的数据库请求代码中,是否可以指定我要返回的某个列自动在其上运行一个函数的方法?

为了澄清起见,我想在提供者php中而不是在 View 文件中进行这些更改,并且我想在具有Accessors的模型之外进行此更改。

最佳答案

我想你可能正在寻找一个集合宏。您可以在 AppServiceProvider 中注册它,例如:

Collection::macro('formatPropUrl', function() {

    return collect($this->items)->map(function($property) {
        $property->prop_url=str_replace("http://domain.com/","http://www.domain.com/",$property->prop_url);

        return $property;
    });

});

然后对于您的查询,您可以执行以下操作:
$featuredProperties = DB::table('properties')
    ->where([
        ['featured_property', '=', '1'],
        ['supplier_id', '=', 123],
    ])
    ->orderBy('prop_id', 'desc')
    ->limit(6)
    ->get()
    ->formatPropUrl();

关于php - 在返回的数据库对象上运行字符串函数的最佳方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40252522/

10-11 02:48
查看更多