如何在helper类中使用laravel Eloquent模型

时间:2015-02-04 21:31:08

标签: php laravel laravel-4 eloquent

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

这是我正在使用的代码。当我使用Category:

时失败了
<?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 个答案:

答案 0 :(得分:2)

如果您的模型不在命名空间内(Laravel 4的默认设置)。加上这个:

use Category;

如果它在名称空间内:

use Your\Namespace\Category;

当然,您始终可以直接指定完全限定的类名。这意味着如果您的类没有命名空间(存在于全局命名空间中),则使用反斜杠以确保您绝对引用它而不是相对于当前命名空间:

$categories = \Category::all();

如果该类恰好位于命名空间中,只需指定完整路径:

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

答案 1 :(得分:0)

你应该没事。你要么这样声明:

use Category;

use Namespace\If\Any\Category;

在助手上课之前,按原样保留其余部分。

或者以这种方式使用它:

$categories = \Category::all();

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