首页 > 解决方案 > Laravel Eloquent 几种关系

问题描述

我为示例制作了三个简单的模型(用户请求获取电话):

  1. User

    • ID
    • 登录
  2. Request

    • ID
    • 用户身份
    • 电话号码
  3. Phone

    • ID
    • 姓名

关系如下:

用户模型中:

public function requests()
{
    return $this->hasMany('App\Requests');
}

手机型号中:

public function phoneRequests()
{
    return $this->belongsTo('App\Requests');
    // But it returns null
}

我需要从 User 模型开始收集一个集合,并获得所有请求的电话(我需要那里的名称)。问题是 phone_id 在请求模型中,而在文档中这是相反的。

我找不到任何关系来达到我的目标。

理想的情况是通过以下关系:

Auth::user()->requests->phoneRequests
// Would returns the phone name the user has requested

我也尝试使用原始 SQL 查询来实现,但我更愿意使用关系。这个怎么做 ?

标签: laravellaravel-5eloquentrelationship

解决方案


您的Requests模型中应该有电话关系,如下所示:

public function phone()
{
    return $this->belongsTo('App\Phone');
}

因此,现在您可以使用手机为用户获取所有请求,如下所示:

$user->requests->first()->phone; // this is for the first request, but you can get the phone for each request in a loop, I guess you know how to do that.

还要注意,您在 Phone 模型中的关系是错误的,因此是 null 的原因。那个应该再次 hasMany 就像在 User 中一样,因为根据您的表结构,电话可以有很多请求。

在你的Phone模型中,你应该有这个:

public function requests()
{
    return $this->hasMany('App\Requests', 'phone_id');
}

因为根据您的数据库结构,电话可以属于许多请求。


推荐阅读