简体   繁体   中英

Get instance of Eloquent model from generic DB query in Laravel 5.1

I have models set with different relationships. Let's say my Entry model belongs to a Supplier , so normally I have a supplier() method in my model file.

So far so good, when I have something like Entry::find(1)->supplier it works wonderfully. However, what is not working is when I grab entries from a generic DB:: query in Laravel, I obviously cannot access the supplier() method because it's not an instance of Entry .

$entries = DB::table('suppliers')
            ->join('entries', "supplier.id", '=', "entries.supplier_id")
            ->select('entries.*')
            ->where("supplier.name", 'like', "%{$name}%")
            ->get();

Now if I dd($entries) ;

I get results as expected. But when I do something like:

dd($entries[0]->supplier); // or ->supplier()

I get this error:

Undefined property: stdClass::$supplier .

So how do I cast (?) these results to the Entry Eloquent model so I can make use of the relationships?


This is a printr of $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
        )

)

As mentioned by @Zakaria, just use Eloquent:

$entries = Entry::with('supplier')
        ->join('supplier', "supplier.id", '=', "entries.supplier_id")
        ->where("supplier.name", 'like', "%{$name}%")
        ->get();

In case you really need to "cast" them, try something like this:

$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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM