![](/img/trans.png)
[英]Not Getting correct model record from query on Eloquent RelationShip Laravel 5.1
[英]Get instance of Eloquent model from generic DB query in Laravel 5.1
我有不同關系的模型。 假設我的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');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.