Laravel:用户和帖子关系

时间:2019-01-16 07:04:04

标签: php laravel

模型结构
user.php

public function inventories() {
   return $this->belongsToMany('App\Model\user\inventory')->orderBY('created_at','DESC')->paginate(10);
}

inventory.php

public function users() {
    return $this->belongsToMany('App\Model\user\user')->withTimestamps();
}  

表结构:

库存:

id
user_id
content

用户:

id
name
email

如何调用inventories->user_id连接到控制器中的users->id
laravel刀片示例:

user_id = 1  
content = 'This is content'  

我想要的是:

user_id = 'Name of user 1'  
content = 'This is content'

2 个答案:

答案 0 :(得分:0)

自定义关系以来,您可以使用:

$inventories = Inventory::all();

foreach ($inventories as $inventory) {

    foreach ($inventory->users as $user) {

         echo $user->name; // show the name of user
    }

    // or to get first user :
    $user_1_name = isset($inventory->users[0]) ? $inventory->users[0]->name : '-';
}

答案 1 :(得分:0)

在您的控制器上:

$inventories = Inventory::all();

在刀片文件上:

@foreach ($inventories as $inventory)
    {{ $inventory->users()->id }}<br/>
@endforeach