【问题标题】:Using Eloquent outside Laravel - Eager/Lazy Loading Related Models在 Laravel 之外使用 Eloquent - 急切/延迟加载相关模型
【发布时间】:2013-12-27 18:34:33
【问题描述】:

我在 wordpress 插件中使用 Laravel 的 Eloquent。

产品型号:

<?php namespace GD;

use Country;

class Product extends \Illuminate\Database\Eloquent\Model
{
    public function country()
    {
        return $this->belongsTo('Country', 'CountryId');
    }
}

国家模式:

<?php namespace GD;

use Product;

class Country extends \Illuminate\Database\Eloquent\Model
{
    public function products()
    {
        return $this->hasMany('Product');
    }
}

我可以使用标准 Laravel 语法查询任何模型:

$products = $this->product->where('MetalId', '=', 1)
->where('ProductTypeId', '=', '2')
->orderBy('Name')->orderBy('CountryId')
->get();

但是我无法急切/延迟加载相关模型:

$products = $this->product->with('country')->where('MetalId', '=', 1)
->where('ProductTypeId', '=', '2')
->orderBy('Name')->orderBy('CountryId')
->get();

错误信息

Fatal error: Class 'Country' not found in .../vendor/illuminate/database/Illuminate/Database/Eloquent/Model.php on line 593

所以我认为这一定是命名空间问题,所以我将模型代码更新为:

return $this->belongsTo('\\GD\\Country', 'CountryId');

and

return $this->hasMany('\\GD\\Product');

但是,当我在产品模型上运行查询并转储结果时,我得到:

  ["relations":protected]=>
  array(1) {
    ["country"]=>
    NULL
  }

【问题讨论】:

  • 您是否配置了类自动加载器?如果另一个插件也包含 Eloquent 文件,你将如何处理这种情况 - 特别是如果它是 Eloquent 的不同版本?

标签: wordpress laravel lazy-loading eloquent eager-loading


【解决方案1】:

我最近也遇到了同样的问题,确实是命名空间问题。

尝试在命名空间字符串中只添加一个反斜杠,因为您使用单引号将它们括起来。

像这样:

return $this->belongsTo('GD\Country', 'CountryId');

and

return $this->hasMany('GD\Product');

另外,请确保您使用的是完整的命名空间。在我的应用中,我使用了“App\Models\ModelName”。

对于您的应用,它应该是类似“App\Models\GD\ModelName”的名称吗?这取决于您的应用程序结构。

让我知道这是否有效。

【讨论】:

  • 顺便说一句,我刚刚注意到模型定义中的命名空间声明。所以'GD\ModelName'是正确的。但是,请尝试使用单反斜杠建议。
  • 谢谢,但是单个 `\` 没有任何区别。
  • 尝试加载单个记录。你能读懂那个记录的国家吗?例如:Product::find(product_id)->country;
  • 嘿。你能做到我在上一条评论中要求的吗?
猜你喜欢
  • 2013-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-25
  • 2017-01-12
  • 1970-01-01
  • 2015-09-30
  • 1970-01-01
相关资源
最近更新 更多