Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何获取hasOne属性的内部视图?_Php_Laravel_Laravel 5 - Fatal编程技术网

Php 如何获取hasOne属性的内部视图?

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

在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 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