【问题标题】:How to get hasOne property inside view?如何在视图中获取 hasOne 属性?
【发布时间】:2017-07-24 10:23:13
【问题描述】:

如何在 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 }}

如果我将 Url model 更改为此

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

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

    使用belongsTo() 关系而不是hasOne()

    public function category()
    {
        return $this->belongsTo('App\Category');
    }
    

    【讨论】:

    • 我照我写的做了,但我发现了问题所在——对于 category_id 中的一些 url,我的值为 NULL。这有效 @if($url->category_id) {{ $url->category->category }} @endif
    猜你喜欢
    • 2022-01-14
    • 2022-01-14
    • 1970-01-01
    • 2019-12-24
    • 2012-03-05
    • 1970-01-01
    • 2019-11-23
    • 2020-12-07
    • 1970-01-01
    相关资源
    最近更新 更多