如何在Urls视图中回显类别名称?我收到这个错误:
Column not found: 1054 Unknown column 'categories.url_id' in 'where clause'
(SQL: select * from `categories` where `categories`.`url_id` = 23 and `categories`.`url_id` is not null limit 1
我相信查询应该是这样的
SELECT * FROM categories WHERE categories.id = 1
网址表
id | url | category_id
1 www.asdf.com 1
类别表
id | category
1 Something
迁移以将列Category_id添加到Urls表
public function up()
{
Schema::table('urls', function(Blueprint $table){
$table->integer('category_id')->unsigned()->nullable();
$table->foreign('category_id')->references('id')->on('urls');
});
}
(嗯,我相信我需要解决这个问题,并提出references('id')->on('categories')
)
网址模型
class Url extends Model
{
protected $table = 'urls';
public function category()
{
return $this->hasOne('App\Category');
}
}
网址索引控制器
$urls = URL::paginate(100)
return view('urls.index')->with('urls', $urls);
Urls.index视图
{{ $url->category->category }}
如果我将网址模型更改为此
public function category()
{
return $this->belongsTo('App\Category');
}
当我执行var_dump($url->category)
时,会生成正确的SQL查询:
select * from `categories` where `categories`.`id` = '1' limit 1
但我仍然无法使用{{ $url->category->category }}
因为错误为Trying to get property of non-object
答案 0 :(得分:1)
使用belongsTo()
关系代替hasOne()
:
public function category()
{
return $this->belongsTo('App\Category');
}