关联查询一致报错,不得已来SF麻烦各位大神帮我解答。
报错内容
ErrorException in 777fb9d9b961f2b2453d93297ba8a847 line 15:
Trying to get property of non-object (View: /home/millyn/www/x.x/resources/views/NewHome.blade.php)
我的对应文件如下
Avatar.php
hasMany('App\Article');
}
}
Article.php
belongsTo('App\Avatar');
}
}
Controller.php
public function index()
{
$articles = Article::with('avatar')->latest()->paginate(8);
return view('NewHome', compact('articles'));
}
NewHome.blade.php
@foreach ($articles as $page)
@endforeach
{!!$articles->render()!!}
article_table.php
public function up()
{
Schema::create('articles', function(Blueprint $table)
{
$table->increments('id');
$table->string('title');
$table->text('body')->nullable();
$table->string('site')->nullable();
$table->integer('avatars_id')->unsigned();;
$table->integer('user_id');
$table->string('nike')->nullable();
$table->timestamps();
$table->foreign('avatars_id')
->references('id')
->on('avatars')
->onDelete('cascade');
});
}
avatars_table.php
public function up()
{
Schema::create('avatars', function(Blueprint $table)
{
$table->increments('id');
$table->string('title');
$table->string('url');
$table->text('path');
$table->timestamps();
});
}
我不知道是哪里有问题,不管怎么弄都是报错..希望大神帮忙看看.谢谢了.
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
你可以dd($articles)来看看,相信在relations这一个上面会是null,总感觉你的relationship声明好奇怪
看第15行输出的是哪个变量,然后dd打印变量,根据问题再逐步排解。
应该是你的调用关联用错了
这里应该用
因为你这里用的是
如果你要改变映射的名字,需要
这之后你要改变很多
谢谢各位的答案,但我是最后自己解决的.
我的解决方案和我挑选的答案是一个方法.
我在
Acticle.php里把内容改成了就行了,关于关联到模板上面的内容是
{{$page->avatar->url}
模型 关联方法 对应字段
非常感谢各位,我也贴出正确解决我问题的方法.
希望可以给以后遇到此类问题的朋友一个解决方案.
其实你只要一路跟 convention 走乖乖地建表就用
avatar_id就不会出这些问题了。另外建议你 hasMany() 关系的时候也用复数
这样写的时候自己也清楚了~