为什么通过user模型可以访问相关联的article模型的属性,但是通过article模型访问user会报错“Attempt to read property "nickname" on null”
小白求教:
在larval9框架下建立了两个模型user和article,两个模型之间是一对多的关系,通过user模型可以访问article模型,但是通过article模型访问user模型就会出错
//user模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\MassAssignmentException;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\DB;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
protected $table='users';
protected $fillable = [
'name',
'email',
'password',
'telephone',
'wx',
'thumb',
'description',
'age',
'school',
'nickname'
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
function ArticleBy(){
return $this->hasMany(Article::class);
}
}
//article模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
use HasFactory;
protected $table='articles';
protected $fillable=[
'Author',
'context',
'mark',
'count',
'like',
'context_alter'
];
function UserBy(){
return $this->belongsTo(User::class);
}
}
//控制器方法
public function article_detail($id){
$article=Article::find($id);
return view('admin.article_detail')->with('article',$article);
}
//前端显示
<div class="article_title">标题:{{$article->title}}</div>
<div class="article_author">作者:{{$article->UserBy->nickname}}</div>
<div class="article_like">点赞数:{{$article->like}}</div>
<div class="article_count">搜索数:{{$article->count}}</div>
<div class="article_cerated">发布时间:{{$article->created_at}}</div>
user表
article表
然后报错提示的SQL信息是“select * from articles
where articles
.id
= ? limit 1”
推荐文章: