Ivan Topić
Ivan Topić

Reputation: 3185

How to get hasOne property inside view?

How can I echo category name when in Urls view? I get this error:

 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

I believe the query should be something like this

SELECT * FROM categories WHERE categories.id = 1

Urls table

id | url | category_id
1    www.asdf.com   1

Categories table

id | category 
1    Something

Migration for adding column Category_id to Urls table

public function up()
{
    Schema::table('urls', function(Blueprint $table){
        $table->integer('category_id')->unsigned()->nullable();
        $table->foreign('category_id')->references('id')->on('urls');
    });
}

(hm I believe I need to fix this and put references('id')->on('categories') )

Url model

class Url extends Model
{

    protected $table = 'urls';

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

}

Url index controller

$urls = URL::paginate(100)
return view('urls.index')->with('urls', $urls);

Urls.index view

{{ $url->category->category }}

If I change Url model to this

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

and when I do var_dump($url->category), the correct SQL query is generated:

select * from `categories` where `categories`.`id` = '1' limit 1

but I still can't get column name with {{ $url->category->category }}

because error is Trying to get property of non-object

Upvotes: 2

Views: 34

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163788

Use belongsTo() relationship instead of hasOne():

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

Upvotes: 1

Related Questions