【问题标题】:Attempt to read property "name" on null LARAVEL 8尝试在 null LARAVEL 8 上读取属性“名称”
【发布时间】:2021-05-25 14:41:26
【问题描述】:

我有以下问题。 事实证明,我想访问模型的关系,或者更确切地说是用户关系的属性与我正在操作的模型本身,但它向我抛出了错误:尝试在 null 上读取属性“名称”。我给你看我的代码。

图像模型

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Image extends Model
{
    protected $table = 'images';

    public function comments(){
        return $this->hasMany(Coment::class);
    }

    public function like(){
        return $this->hasMany(Like::class);
    }

    public function user(){
        return $this->belongsTo(User::class, 'user_id');
    }
}

web.php // 路由存档

Route::get('/', function () {

    $images = Image::all();
    foreach($images as $image){
        echo $image->imagen_path. "<br/>";
        echo $image->description. "<br/>";
        echo $image->user->name." ".$image->user->surname;
        die();
        if(count($image->comments) >= 1){
            echo "<h4>Comentarios</h4>";
            foreach($image->comments as $comment){
                $comment->user->name. " " .$comment->user->surname.":";
                $comment->content. "<br/>";
            }
        }
        echo "<hr/>";
    }

    die();
    return view('welcome');
});

问题是为什么它不允许我输入用户对象的名称属性。我在 laravel 8 中

【问题讨论】:

  • 可能是因为在你们的关系中,你的类名Coment有错别字
  • 您确定$image-&gt;user 存在吗,当您尝试转储它时会发生什么?也不确定是否拼写错误,但在Image 类中定义comments,但类是Coment
  • 问题在这里无论如何都会出现$ image-> user-> name。随着我的进步,我将纠正其他关系,但我的问题出现了,因为它没有识别 $ image 中与用户关系的名称属性。如果 $ image-> 用户存在。
  • 正如@Rooneyl 所说,当您dd($image-&gt;user) 时会发生什么?我认为您如何定义关系上的链接字段存在错误,但在不知道架构的情况下,我不能说。
  • @Tomaguilera 没有问题,将修复作为答案发布,以便其他发现此问题的人受益

标签: laravel eloquent orm relationship


【解决方案1】:

我找到了解决问题的方法。

在 Image 模型中,我在 user() 方法中建立关系,并在里面写:

return $ this-> belongsTo (User :: class, 'user_id');

问题出在错误的参数上,实际上是users_id,我错过了s

【讨论】:

    猜你喜欢
    • 2021-08-08
    • 2021-06-25
    • 2021-05-17
    • 2022-06-10
    • 2022-11-16
    • 2022-10-12
    • 2021-05-22
    • 2022-01-04
    • 2023-01-28
    相关资源
    最近更新 更多