尝试在 null 上读取属性“名称”

新手上路,请多包涵

品类模型

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();
        });
    }

原文由 Emre Ensar Çapcı 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 296
1 个回答

您需要在定义类别关系时明确定义您的类别外键。因为你的category外键不是category_id;它是 cat_id。

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

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

原文由 mrdev 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏