我的模型设置了不同的关系。假设我的Entry
模型属于Supplier
,因此通常supplier()
我的模型文件中都有一个方法。
到目前为止,一切顺利,当我拥有类似功能时Entry::find(1)->supplier
,效果非常好。但是,当我从Laravel中的通用DB ::查询中获取条目时,不起作用的是,我显然无法访问该supplier()
方法,因为它不是的实例Entry
。
$entries = DB::table('suppliers')
->join('entries', "supplier.id", '=', "entries.supplier_id")
->select('entries.*')
->where("supplier.name", 'like', "%{$name}%")
->get();
现在如果我dd($entries)
;
我得到预期的结果。但是当我做类似的事情时:
dd($entries[0]->supplier); // or ->supplier()
我收到此错误:
未定义的属性:stdClass :: $ supplier。
那么,如何将这些结果转换为(?)到Entry
Eloquent模型,以便可以利用这些关系?
这是一个printr
的$entries
:
Array
(
[0] => stdClass Object
(
[id] => 1
[user_id] => 0
[archived] => 0
[supplier_id] => 5
[customer_id] => 1
[contact] => dfgfdg
[commission] => dfgdfg
[entrance_date] => 2015-09-22 16:52:33
[cost_estimate] => 1
[status] => 1
[type] => 1
[watch_id] => 7
[reference] => dfgdfg
[serial_number] => 0
[delivery_date] => 2015-09-07 16:52:33
[articles_json] =>
[total_sales_cost_netto] =>
[gross_profit_netto] =>
[gross_profit_brutto] =>
[created_at] => 2015-09-09 20:10:02
[updated_at] => 2015-09-11 16:52:33
)
)
如@Zakaria所述,只需使用Eloquent:
$entries = Entry::with('supplier')
->join('supplier', "supplier.id", '=', "entries.supplier_id")
->where("supplier.name", 'like', "%{$name}%")
->get();
如果您确实需要“投射”它们,请尝试如下操作:
$entries = $yourDbQuery;
$c = new \Illuminate\Database\Eloquent\Collection;
foreach ($entries as $entry) {
$entryModel = new \App\Entry;
$c->add($entryModel->forceFill((array)$entry));
}
$c->load('supplier');
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句