为什么通过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”

《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
最佳答案

因为 article 模型对应的 user 模型没有数据吧,后面你反问user数据就报错了

1年前 评论
yuantao (楼主) 1年前
deatil (作者) 1年前
yuantao (楼主) 1年前
讨论数量: 8

因为 article 模型对应的 user 模型没有数据吧,后面你反问user数据就报错了

1年前 评论
yuantao (楼主) 1年前
deatil (作者) 1年前
yuantao (楼主) 1年前
李铭昕

这样问问题,100% 找不到解决办法。

你至少把自己的代码贴出来,有可能你只 select 了 id,当通过 article 找 user 的时候因为没有查询 user_id 自然找不到。能造成这个结果的原因至少 3 种。

你是让我们给你穷举出所有可能性,你一个一个试试么?

1年前 评论
yuantao (楼主) 1年前
李铭昕

通过 article 模型访问 user 模型会出错,应该贴 article 的模型吧。

不过我看你说已经解决了,那我给你一个建议,不要太依赖模型的自动找关联 ID 的能力,

比如 hasMany 有三个方法,你可以把 模型、local_id、foreign_id 都写上,基本可以杜绝这个问题

1年前 评论
yuantao (楼主) 1年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!