简体   繁体   中英

Laravel one to many relation

Cannot seem to find what I am doing wrong anymore after trying to get something else to work using polymorphic relations.. I have two tables setup:

Payments:

- id
- name
- etc..

Deposits:

- id
- payment_id
- name
- etc..

My model relationships:

Payment:

public function deposits()
{
    return $this->hasMany(Deposit::class);
}

Deposit:

public function payments()
{
    return $this->belongsTo(Payment::class);
}

Now I have one record in each table for testing purposes. I am trying to eager load the payments when displaying the deposits:

For example:

$deposits = Deposit::with('payments')->get();

This does not return the payment that is associated with it, just returns null for the relation. In my table the payment_id is 1, just as the id in the payments table. To my recollection, this should work. What am I missing?

Edit, the getQueryLog returns this:

array(3) { [0]=> array(3) { ["query"]=> string(52) "select * from `users` where `users`.`id` = ? limit 1" ["bindings"]=> array(1) { [0]=> int(1) } ["time"]=> float(0) } [1]=> array(3) { ["query"]=> string(24) "select * from `deposits`" ["bindings"]=> array(0) { } ["time"]=> float(0) } [2]=> array(3) { ["query"]=> string(53) "select * from `payments` where `payments`.`id` in (?)" ["bindings"]=> array(1) { [0]=> int(0) } ["time"]=> float(0) } }

在此处输入图片说明

Changed my relation in my Deposit model and it works:

public function payment()
{
    return $this->belongsTo(Payment::class, 'payment_id');
}

Still figuring out why I have to add it, since it should work without it as well.

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