laravel pluck 5.2不适用于5.1

时间:2016-03-10 10:27:36

标签: laravel laravel-5.2

下面的代码在5.1中工作,它是延迟加载徽标。但现在它试着在Collection上调用load方法。

$campaigns = Campaign::all();
$campaigns->pluck('brand')->load('logo');

错误

in Macroable.php line 81
at Collection->__call('load', array('logo')) in HomeController.php line 84
at Collection->load('logo') in HomeController.php line 84
at HomeController->index(object(Request))

5.1错误的关系错误

in Builder.php line 2071
at Builder->__call('logo1', array())
at Builder->logo1()
at call_user_func_array(array(object(Builder), 'logo1'), array()) in Builder.php line 943
at Builder->__call('logo1', array())
at Builder->logo1()
at call_user_func_array(array(object(Builder), 'logo1'), array()) in Model.php line 3483
at Model->__call('logo1', array()) in Builder.php line 477
at Brand->logo1() in Builder.php line 477
at Builder->Illuminate\Database\Eloquent\{closure}()
at call_user_func(object(Closure)) in Relation.php line 171
at Relation::noConstraints(object(Closure)) in Builder.php line 478
at Builder->getRelation('logo1') in Builder.php line 449
at Builder->loadRelation(array(object(Brand), object(Brand), object(Brand), object(Brand), object(Brand), object(Brand), object(Brand)), 'logo1', object(Closure)) in Builder.php line 429
at Builder->eagerLoadRelations(array(object(Brand), object(Brand), object(Brand), object(Brand), object(Brand), object(Brand), object(Brand))) in Collection.php line 44
at Collection->load('logo1') in HomeController.php line 82

找出它是Illuminate \ Database \ Eloquent \ Collection,现在是Illuminate \ Support \ Collection。

如何将其转换为Eloquent?

2 个答案:

答案 0 :(得分:0)

使用pluck结果初始化一个新的Eloquent集合,它再次起作用。我希望有更好的解决方案。

    $b = new \Illuminate\Database\Eloquent\Collection($campaigns->pluck('brand'));
    $b->load('logo');

答案 1 :(得分:0)

您应该检查Laravel文档here:如引言中所述

  

注意:虽然大多数Eloquent集合方法返回Eloquent集合的新实例,但pluck,keys,zip,collapse,flatten和flip方法返回一个基本集合实例。

Eloquent Collection只是Illuminate \ Support \ Collection的延伸。在Eloquent Collection中,构造函数不会被覆盖,因此,检查Base Controller构造函数,我们可以假设您可以使用这种类型/实例创建一个Eloquent Collection(或一个新的Base Collection):

  • 阵列
  • 集合( self 的实例)
  • 可数组(实例)
  • Jsonable(实例)
  • JsonSerializable(实例)

您可以将Collection类的__construct方法检查到您的vendor文件夹,检查到laravel \ framework \ Illuminate \ Support \ Collection.php,然后搜索调用到构造函数中的getArrayableItems方法。

我认为,从“基础”集合创建一个Eloquent集合是没有用的,因为您将丢失对数据库的引用,您将无法再直接使用该结果集。实际上,您将没有id或任何主键,可以让您在数据库中标识精确的行(除非您的弹拨数据是主键)。无论如何,你可以在构造函数中实例化一个新的Eloquent集合,传递“base”集合:

$baseCollection = new \Illuminate\Support\Collection();
$eloquentCollection = new \Illuminate\Database\Eloquent\Collection($baseCollection);

此外,使用Campaign :: all(),您将从表中获取所有列。你为什么不

Campaign::with('logo')->get(['id', 'brand']);

延迟加载将对集合中的每个元素进行查询。相反,热切加载将以更快的方式执行它,在少量查询中提供您需要的所有数据。