【问题标题】:Error : Trying to get property of non-object错误:试图获取非对象的属性
【发布时间】:2018-05-23 11:32:53
【问题描述】:

我有表Authors 和表Uploads,我只是想通过author_idUploads 表中获取某个作者的所有上传。

为此,我的控制器中有一个方法,如下所示:

public function author_works()
    {

        $uploads= Upload::where('author_id', 3)->first();

        return view('author-works')->with('uploads',$uploads);
    }

我的看法是:

  @extends('layouts.app')
@section('content')
    <h1>Uploads</h1>
    @if(count($uploads)>0)
        @foreach($uploads as $upload)
            <div class="well">
                <h3><a href="/uploads/{{$upload->id}}">{{$upload->name}}</a> </h3>
                <small>Written on {{$upload->created_at}}</small>

            </div>
        @endforeach
      {{--  {{$uploads->links()}}--}}
    @else
        <p>No uploads found</p>
    @endif

@endsection

当我在控制器中使用dd($uploads); 进行调试时,我看到以下内容,这实际上是正确的记录:

 #attributes: array:9 [▼
    "id" => 7
    "name" => "Fsdf"
    "description" => "fsdfsdffds"
    "created_at" => "2017-12-07 21:29:53"
    "updated_at" => "2017-12-07 21:29:53"
    "user_id" => 1
    "avtor_id" => 3
  ]
  #original: array:9 [▼
    "id" => 7
    "name" => "Fsdf"
    "description" => "fsdfsdffds"
    "created_at" => "2017-12-07 21:29:53"
    "updated_at" => "2017-12-07 21:29:53"
    "user_id" => 1
    "avtor_id" => 3
  ]

谁能解释我为什么会收到错误消息?

【问题讨论】:

  • first 只会给你一条记录,所以你不能在一条记录中使用循环,而是使用get() 函数

标签: laravel laravel-5 eloquent


【解决方案1】:

当您使用first() 方法时,you're getting an object instead of collection。使用get():

$uploads = Upload::where('author_id', 3)->get();

【讨论】:

  • 感谢您的回答以及指向您其他人的链接。它有帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-08
  • 2016-06-13
  • 2018-06-02
  • 2017-08-20
  • 1970-01-01
相关资源
最近更新 更多