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

Bil*_*son 2 php laravel eloquent laravel-4

如何在控制器之外使用 Laravel Eloquent 模型?我似乎不知道use "*insert class here*"我应该使用什么声明。我有一个帮助类,它将经常使用我的“类别模型”。

这是我正在使用的代码。当我使用类别时它失败:

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

}
Run Code Online (Sandbox Code Playgroud)

luk*_*ter 5

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

use Category;
Run Code Online (Sandbox Code Playgroud)

如果它位于命名空间内:

use Your\Namespace\Category;
Run Code Online (Sandbox Code Playgroud)

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

$categories = \Category::all();
Run Code Online (Sandbox Code Playgroud)

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

$categories = Your\Namespace\Category::all();
Run Code Online (Sandbox Code Playgroud)