尝试在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');
}
相关文章