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

《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
最佳答案

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

2个月前 评论
yuantao (楼主) 2个月前
deatil (作者) 2个月前
yuantao (楼主) 2个月前
讨论数量: 8

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

2个月前 评论
yuantao (楼主) 2个月前
deatil (作者) 2个月前
yuantao (楼主) 2个月前
李铭昕

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

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

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

2个月前 评论
yuantao (楼主) 2个月前
李铭昕

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

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

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

2个月前 评论
yuantao (楼主) 2个月前

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