【问题标题】:Laravel: User & Post RelationshipLaravel:用户和帖子关系
【发布时间】:2019-01-16 15:56:48
【问题描述】:

模型结构
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'

【问题讨论】:

标签: php laravel


【解决方案1】:

既然你已经定义了你的关系,你可以使用:

$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 : '-';
}

【讨论】:

  • 我刚刚找到答案-_- here
【解决方案2】:

在您的控制器上:

$inventories = Inventory::all();

在您的刀片文件上:

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

【讨论】:

    猜你喜欢
    • 2014-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 2014-07-25
    • 2018-07-26
    • 2019-01-22
    • 1970-01-01
    相关资源
    最近更新 更多