如何利用修补程序找出laravel模型中的反比关系

时间:2017-10-24 11:31:04

标签: php laravel eloquent laravel-5.3

我得到了这个课程

getSupportFragmentManager()

找到属于商店的零售商工作得很好:

namespace App;

use Illuminate\Database\Eloquent\Model;

class RetailerInfo extends Model
{

    public function user()
    {
        //same as retailer() but more consistent
        return $this->belongsTo(User::class, 'retailer_id');
    }

    public function store()
    {
        return $this->belongsTo(Store::class);
    }
}

但找到商店所属的用户不起作用:

>>>namespace App;
>>>Store::find(2)->RetailerInfo
=> App\RetailerInfo {#1144
     id: 1,
     retailer_id: 65,
     store_id: 2,
     created_at: "2016-07-16 09:47:43",
     updated_at: "2016-07-16 09:47:43",
   }

如何让它发挥作用?

1 个答案:

答案 0 :(得分:1)

正如documentation所说,你只需要声明一次关系,并在模型的方法中声明

您使用此示例做了什么

RetailerInfo::find(1)->belongsTo(User::class);

不正确,因为你不会在旅途中宣布关系。

而是使用您在模型中声明的关系(StoreRetailerInfo有关系,RetailerInfo已与User有关系

Store::find(2)->RetailerInfo->user;