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