Laravel Eloquent显示多个表格的结果

时间:2018-02-27 12:25:20

标签: php laravel eloquent

我正在尝试创建一个基本日志程序,每个日志条目都与使用其id的用户相关联,我无法在表格上显示整个日志条目并使用模型之间的关系来显示用户在表中命名而不是他的id,理解任何帮助以解释语法以及为什么关系没有显示。

我的控制员:

public function index()
{
    $dcmlogs = log::with('users')->get();

   return view('dcmlog.index', compact('dcmlogs'));
 }

日志模型:

public function users()
    {
        return $this->belongsTo('App\User','user_id');
    }

用户模型:

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

观点:   现场用户 - >看起来很空洞,里面没有任何东西。

@foreach($dcmlogs as $post)
      <tr>
        <td>{{$post['users->name']}}</td>
        <td>{{$post['description']}}</td>
        <td>{{$post['action']}}</td>
        <td>{{$post['type']}}</td>
        <td>{{$post['comment']}}</td>
        <td>{{$post['created_at']}}</td>

这是我的日志表

$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');

我做错了什么?

编辑:输出dd(dcmlogs)

Collection {#220 ▼
  #items: array:3 [▼
    0 => log {#226 ▼
      #table: "logs"
      #fillable: array:4 [▼
        0 => "action"
        1 => "description"
        2 => "comment"
        3 => "type"
      ]
      #connection: "mysql"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:8 [▶]
      #original: array:8 [▼
        "id" => 1
        "type" => "volvo"
        "action" => "okoko"
        "description" => "okok"
        "comment" => "kokok"
        "user_id" => 1
        "created_at" => "2018-02-27 07:57:19"
        "updated_at" => "2018-02-27 07:57:19"
      ]
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: array:1 [▼
        "users" => User {#231 ▼
          #table: "users"
          #fillable: array:3 [▶]
          #hidden: array:2 [▶]
          #connection: "mysql"
          #primaryKey: "id"
          #keyType: "int"
          +incrementing: true
          #with: []
          #withCount: []
          #perPage: 15
          +exists: true
          +wasRecentlyCreated: false
          #attributes: array:7 [▼
            "id" => 1
            "name" => "alex"
            "email" => "ijijij@gmail.com"
            "password" => "$2y$10$fSk7n1JqNTp2bQL/iBfXfOIetXOfpPhLBhu/S3mwp3CeLJi"
            "remember_token" => "lCx9FtWOHEGQmpP1bX9XtxFGdN3vCS6OAxkrO2AAei4ARtlrUa6KpmNG"
            "created_at" => "2018-02-27 07:56:45"
            "updated_at" => "2018-02-27 07:56:45"
          ]

1 个答案:

答案 0 :(得分:0)

您正试图获取$post类似数组的属性,但$postobject。将您的foreach更改为:

@foreach($dcmlogs as $post)
  <tr>
    <td>{{$post->users->name}}</td>
    <td>{{$post->description}}</td>
    <td>{{$post->action}}</td>
    <td>{{$post->type}}</td>
    <td>{{$post->comment}}</td>
    <td>{{$post->created_at}}</td>
@endforeach