php – 从Laravel 5.1中的通用数据库查询中获取Eloquent模型的实例

我有不同关系的模型.假设我的Entry模型属于供应商,所以通常我的模型文件中有一个supplier()方法.

到目前为止一切都那么好,当我有一些像Entry :: find(1) – >供应商这样的产品时,效果非常好.然而,什么是无效的是当我从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()

我收到此错误:

Undefined property: stdClass::$supplier.

那么如何将(?)这些结果转换为Entry Eloquent模型,以便我可以利用这些关系?

这是$条目的原则:

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');
点赞