2015-02-04 30 views
0

如何在控制器外部使用laravel雄辩模型?我似乎无法找出我应该使用的语句use "*insert class here*"。我有一个助手类,经常会使用我的“类别模型”。如何在助手类中使用laravel雄辩模型

这是我使用的代码。当我使用类别:

<?php 

namespace Msh\Redirects; 

use Illuminate\Support\Facades\Config as Config; 
use Illuminate\Support\Facades\Input as Input; 


/** 
* This is the actual "product class" that generates the 301 redirect url's 
* 
* This is the product 
* 
* @author bgarrison 
*/ 
class StorefrontRedirectsGenerator implements RedirectsGenerator { 

    public function generateUrls() { 
     // Set the database to the name of the domain 
     Config::set('database.connections.mysql_tenant.database', Input::get('domain')); 

     // Grab all the categories 
     $categories = Category::all(); 

     // Use category information to determine request url's and target url's 
     $urlMapping = []; 
     $count = 0; 
     $categoryCount = 0; 
     foreach ($categories as $category) { 
      if ($category->Published == 1) { 
       $oldUrl = 'c-' . $category->CategoryID . '-' . $category->SEName . '.aspx'; 
       $urlMapping['category_urls'][$oldUrl][] = $category->SEName . '.html'; 
       $count++; 
       $categoryCount++; 
      } 
      if ($category->ParentCategoryID !== '0') { 
       $parentCategory = Category::where('CategoryID', '=', (int) $category->ParentCategoryID)->get(); 
       foreach ($parentCategory as $pcategory) { 
        $url = $pcategory->SEName . '/' . $urlMapping['category_urls'][$oldUrl][0]; 
        if (!in_array($url, $urlMapping['category_urls'][$oldUrl])) { 
         $urlMapping['category_urls'][$oldUrl][] = $url; 
         $count++; 
         $categoryCount++; 
        } 
       } 
      } 
     } 
     $urlMapping['category_urls']['count'] = $categoryCount; 
     return Response::json([ 
       'success' => true, 
       'count' => $count, 
       'data' => $urlMapping 
     ]); 
    } 

} 

回答

2

如果您的模型不在名称空间内(使用Laravel 4的默认设置)。如果它是一个命名空间内

use Category; 

:添加此

use Your\Namespace\Category; 

当然,你总是可以直接指定完全合格的类名。这意味着,如果你的类没有命名空间(在全局命名空间中存在的话)你用一个反斜杠,以确保你引用它绝对的,而不是相对于当前命名空间:

$categories = \Category::all(); 

而且如果类恰好是在命名空间,只需指定完整路径:

$categories = Your\Namespace\Category::all(); 
+0

这做到了!万分感谢。我仍然习惯了这些年后的命名空间:) –

+0

不客气:) – lukasgeiter

+0

我会将它标记为答案asap –

0

你应该没问题。你要么声明它是这样的:

use Category; 

use Namespace\If\Any\Category; 

前助手类,剩下的为是。

或者使用这种方式:

$categories = \Category::all(); 

$categories = Namespace\If\Any\Category::all(); 
+0

我希望我可以将这两个标记作为答案,但作为卢卡斯首先回答我将标记为答案。 –