gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 09:22:48 25 4
gpt4 key购买 nike

如何在 Controller 之外使用 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
]);
}

}

最佳答案

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

use Category;

如果它在命名空间内:

use Your\Namespace\Category;

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

$categories = \Category::all();

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

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

关于php - 如何在 helper 类中使用 laravel Eloquent 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28331843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com