laravel模型提供了一种方法,可以从另一个关联表返回结果,这很方便.
例如,我有一个名为item的表和另一个名为feedback的表,其中feedback表存储item表中某个项目的反馈.因此,为了获得id为1的项目的所有反馈,我将执行以下操作:
Item::find(1)->feedback;
接下来是这个对象的打印输出.
Illuminate\Database\Eloquent\Collection Object
( [items:protected] => Array
(
[0] => Feedback Object
(
[table:protected] => feedback
[connection:protected] =>
[primaryKey:protected] => id
[perPage:protected] => 15
[incrementing] => 1
[timestamps] => 1
[attributes:protected] => Array
(
[id] => 1
[rma_id] => 3
[item_id] => 8
[quo_id] => 0
[case_id] => i2eM20160120
[line_no] => 000001
[content] => test
[status] => sent
[read] => 0
[sender] => Tester
[created_at] => 2016-01-20 18:03:44
[updated_at] => 2016-01-20 18:03:44
)
[original:protected] => Array
(
[id] => 1
[rma_id] => 3
[item_id] => 8
[quo_id] => 0
[case_id] => i2eM20160120
[line_no] => 000001
[content] => test
[status] => sent
[read] => 0
[sender] => Tester
[created_at] => 2016-01-20 18:03:44
[updated_at] => 2016-01-20 18:03:44
)
[relations:protected] => Array
(
)
[hidden:protected] => Array
(
)
[visible:protected] => Array
(
)
[appends:protected] => Array
(
)
[fillable:protected] => Array
(
)
[guarded:protected] => Array
(
[0] => *
)
[dates:protected] => Array
(
)
[touches:protected] => Array
(
)
[observables:protected] => Array
(
)
[with:protected] => Array
(
)
[morphClass:protected] =>
[exists] => 1
)
)
)
它工作正常,并且显示只有一个关于id为1的项目的反馈.
我担心的是数据集在[attributes:protected]
和[original:protected]
中重复.这只是一个测试 case ,真正的 case 将包含数千条反馈,而拥有一个重复的数据集是对内存的巨大浪费.如果我使用DB::table('table_name')
方法,数据集不会被复制,但这就不那么方便了.
为什么laravel需要复制模型中的数据?
有没有办法让它只返回一组数据?
目前,我使用->toArray()
在查询后立即减少不必要的数据,但内存使用率仍然存在,因为laravel仍在创建该数据集.