douzhangwei5265 2018-03-26 14:38
浏览 231
已采纳

试图获取非对象的属性 - Laravel

There are lot of issues with this same topic but in my code, i don't see my error to be getting

Trying to get property of non-object

My models also seems alright. Could the issue results from my database relation?

Parents

  public function up()
    {

        Schema::create('parents', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('phone');
            $table->integer('user_id')->unsigned()->nullable();
            $table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade'); 

            $table->timestamps();
        });
    }

Child

public function up()
    {
        Schema::create('children', function (Blueprint $table) {
            $table->increments('id');
            $table->string('parent_phone')->references('phone')->on('parents')->onUpdate('cascade')->onDelete('cascade'); 
            $table->timestamps();
        });
    }

ChildModel

public function parents(){
      return $this->belongsTo(Parent::class, 'parent_phone');
  }

View

 @foreach ($item->parents as $parent)
        <td>{{ $parent->child }} <br/>
        <small>{{ $parent->created_at }}</small>
        <br>
        <small>{{ $parent->parents->name }}</small>

        </td>
      @endforeach
  • 写回答

1条回答 默认 最新

  • dongqi7631 2018-03-26 14:53
    关注

    Your relationship is not quite right.

    Because your foreign key (parent_phone) is not referencing the primary key (id) on the parents table, you need to specify the name of the field on parents that it references. This is done using the third parameter to the belongsTo() method. Your relationship should look like:

    public function parents(){
        return $this->belongsTo(Parent::class, 'parent_phone', 'phone');
    }
    

    You can read more about Eloquent relationships in the documentation here.

    Even after correcting the relationship, your view may still return this error because of this line:

    {{ $parent->parents->name }}
    

    If your parent record does not have a parent record, you will be attempting to access ->name on null, and that'll throw the error.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动