Php 如何获取hasOne属性的内部视图?
在URL视图中如何回显类别名称?我得到这个错误:Php 如何获取hasOne属性的内部视图?,php,laravel,laravel-5,Php,Laravel,Laravel 5,在URL视图中如何回显类别名称?我得到这个错误: 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 catego
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
URL表
id | url | category_id
1 www.asdf.com 1
id | category
1 Something
类别表
id | url | category_id
1 www.asdf.com 1
id | category
1 Something
向URL表添加列类别\u id的迁移
public function up()
{
Schema::table('urls', function(Blueprint $table){
$table->integer('category_id')->unsigned()->nullable();
$table->foreign('category_id')->references('id')->on('urls');
});
}
(嗯,我认为我需要解决这个问题,并将引用('id')->放在('categories')
)
Url模型
class Url extends Model
{
protected $table = 'urls';
public function category()
{
return $this->hasOne('App\Category');
}
}
Url索引控制器
$urls = URL::paginate(100)
return view('urls.index')->with('urls', $urls);
url.index视图
{{ $url->category->category }}
如果我将Url模型更改为此
public function category()
{
return $this->belongsTo('App\Category');
}
当我执行var\u dump($url->category)
时,会生成正确的SQL查询:
select * from `categories` where `categories`.`id` = '1' limit 1
但是我仍然无法使用{{$url->category->category}}
因为错误是尝试获取非对象的属性使用belongsTo()
关系而不是hasOne()
:
我按照我写的那样做了,但是我发现了问题所在——对于category_id中的一些URL,我的值为空。这适用于@if($url->category_id){{{$url->category->category}}@endif