Laravel:一个用户可以有很多设备,但每个设备最多只属于一个用户


Laravel: A User can have many devices but every device belongs to maximum one user

我有点卡住了。

所以我有两个模型,UserDevice。一个用户可以有X个设备,但每个设备最多只能属于一个用户。

我定义了这样的关系:

class Device extends Model
{
    public function user()
    {
        return $this->hasOne('App'User');
    }
}
class User extends Authenticatable
{
    public function devices()
    {
        return $this->hasMany('App'Device');
    }
}

现在,我想要我的设备的概览视图。

class DeviceController extends Controller
{
    public function showOverview()
    {
        $devices = Device::all();
        return view('devices.overview')->with('devices', $devices);
    }
}

在此视图中,我预览了所有设备。

@foreach ($devices as $device)
    <tr>
        <td>{{ $device->id }}</td>
        <td>{{ $device->serial }}</td>
        <td>{{ $device->state }}</td>
        <td><!-- Get user Name here by $device->user_id Foreign key --></td>
        <td>
            <a href="" class="btn btn-block btn-primary btn-sm">
                <i class="fa fa-user" aria-hidden="true"></i> Profile
            </a>
        </td>
    </tr>
@endforeach

在那里,注释所在的位置,我想获取关联的用户名。外键保存为$device->user_id,并引用users表的id。如何获取该用户的名称?

首先,您应该为所有设备渴望加载相关的用户,以避免每次访问相关的user模型时都会出现额外的数据库查询。

更换

$devices = Device::all();

带有

$devices = Device::with('user')->get();

其次,为了访问模板中相关的User对象,只需执行以下操作:

<td>{{ $device->user->name }}</td>
$device->user->name // or other properties of user

Device

return $this->belongsTo("App'User");

当外键不在引用表中时,应使用hasOne。在您的情况下,外键user_id在引用表devices中,因此这是一个belongsTo关系

用户模型上有正确的关系设置,但设备模型上的关系相反应使用belongsTo()方法,而不是hasOne()方法。

class Device extends Model
{
    public function user()
    {
        return $this->belongsTo(App'User::class);
    }
}

然后,您应该能够使用刀片模板中的以下内容获取给定设备的用户名。

{{ $device->user->name }}

当你在设备结果上循环时,你也在访问每个模型的用户关系,你可能希望急于加载用户关系,以最大限度地减少对数据库的查询量

$devices = Device::with('user')->get();

您还可以仅为给定用户查询设备

$user->devices