沃梦达 / 编程问答 / php问题 / 正文

尝试在NULL上读取属性&Quot;Name&Quot;

Attempt to read property quot;namequot; on null(尝试在NULL上读取属性Quot;NameQuot;)

本文介绍了尝试在NULL上读取属性&Quot;Name&Quot;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类别模型

class Category extends Model
{
use HasFactory;

protected $fillable= ['name','number'];

 public function news(){

    return $this->hasMany(News::class);
}

新闻模型

class News extends Model
{
use HasFactory;

protected $fillable= ['cat_id','title','photo','description','author_id','status'];

 public function category(){
        return $this->belongsTo(Category::class);
    }

  public function author(){
  return $this->belongsTo(Author::class);
    }

作者模型

class Author extends Model
{
use HasFactory;

protected $fillable= ['name','status'];

public function news(){
    return $this->hasMany(News::class);
}

这3个模型之间有关系。并且我想在news-list.blade.php中显示类别名称而不是CATEGORY_ID。我收到此错误。

这是我的控制器函数

  public function news_index(){
    $news= News::with('category')->get();
    return view('News.list',compact('news'));
}

这是我的刀片页面。当我键入$new->category->name而不是cat_id时出错。

@foreach($news as $new)
            <tr>
                <th scope="row">{{$loop->iteration}}</th>
                <td> {{$new->category->name}}</td>
                <td>  {{$new->title}}</td>
                <td> @if($new->photo)
                        <a href="{{url('storage/images/'.$new->photo)}}" target="_blank" class="btn btn-sm btn-secondary">Görüntüle</a></td>
                @endif
                </td>
                <td>  {{$new->author_id}}</td>
                <td>  {{$new->description}}</td>
                <td>  {{$new->status}}</td>

                <td>
                    <a class="btn btn-danger" onclick="return confirm('Silmek istediğinize emin 
       misiniz?')" href="{{route('news_delete', $new->id)}}"><i class="fa fa-trash"></i></a>
                    <a class="btn btn-primary" href="{{route('news_update',$new->id)}}"><i class="fa 
      fa-pen"></i></a>

                </td>
            </tr>
        @endforeach
 

这是我的新闻迁移表

public function up()
    {
        Schema::create('news', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('cat_id');
            $table->string('title');
            $table->string('photo');
            $table->longText('description');
            $table->unsignedBigInteger('author_id');
            $table->boolean('status')->default('1');
$table->foreign('cat_id')->references('id')->on('categories')->onDelete('cascade');
            $table->foreign('author_id')->references('id')->on('authors')->onDelete('cascade');
            $table->timestamps();
        });
    }

推荐答案

您需要在定义类别关系时显式定义类别外键。因为您的类别外键不是CATEGORY_ID;而是cat_ID。

例如,您需要定义News模型中的类别关系,如下所示:

public function category()
{
    return $this->belongsTo(Category::class, 'cat_id');
}

这篇关于尝试在NULL上读取属性&Quot;Name&Quot;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:尝试在NULL上读取属性&Quot;Name&Quot;

基础教程推荐