简体   繁体   中英

Hasone returns null in laravel 5.4

I have in my transaction mode:

public function order()
{
    return $this->hasOne('Model\Interaction\Order');
}

I want to get the order with the transaction,

Transaction::where('id', 1)->with('order')->get();

but order is empty. In transactions table I have order_id .

What am I doing wrong?

Thanks

You should have transaction_id in the orders table if you define relationship like that.

Since you have order_id in the transactions table, relationship should be belongsTo() :

public function order()
{
    return $this->belongsTo('Model\Interaction\Order');
}

由于order_id位于交互表上,因此应使用belongsTo而不是hasOne

In my case, the problem was that the child table ie the relation I thought had one actually had multiple entries with the same value. Eloquent doesn't select all the relations with matching IDs and slice 1 for you. So, if you say

public function foo ()
 return $this->hasOne(Bar::class, 'this_class_id');
}

ensure that Bar 's table column this_class_id is indeed unique or else you'll stay getting null results

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