Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to set a 1 to many relationship in the same table in Laravel 4

I have the following models

Category:

<?php

class Category extends Eloquent {
    protected $table = "category";
    protected $fillable = array('title','parent','metatit','metadsc','metake','metaurl','image');
    public function categoryitems(){
        return $this->hasMany('CategoryItem','catid');
    }
    public function parent(){
        return $this->hasMany('category','parent');
    }
    public function child(){
        return $this->belongsTo('Category','parent');
    }
}

Need to set a 1 to many relationship in the category table Ex category "cities" is a child of category "countries"

the error happen when i try to use the following code

<?php

$parent = Category::where('id','=',$cat->id)->parent;
echo $parent->title;

?>

The error :

ErrorException (E_UNKNOWN) Undefined property: Illuminate\Database\Eloquent\Builder::$parent (View: /var/www/phpWithAngulerJS/app/views/admin/category-edit.blade.php)

like image 742
Bassem Aiad Avatar asked Mar 08 '15 18:03

Bassem Aiad


People also ask

What is belongsToMany in laravel?

hasMany is used in a One To Many relationship while belongsToMany refers to a Many To Many relationship. They are both distinct relationship types and each require a different database structure - thus they take different parameters.

What is the use of whereHas in laravel?

Laravel eloquent whereHas() method works basically the same as has() but it just allows you to specify additional filters for the related model to check.

Does laravel 8 have one relation?

hasOne relationship in laravel is used to create the relation between two tables. hasOne means create the relation one to one. For example if a article has comments and we wanted to get one comment with the article details then we can use hasOne relationship or a user can have a profile table.


1 Answers

First off, fix the relations as follows:

public function children() {
    return $this->hasMany('Category','parent');
}
public function parent() {
    return $this->belongsTo('Category','parent');
}

And your query needs to be executed first:

$parent = Category::where('id','=',$cat->id)->first()->parent;
// btw since you have $cat, you probably can do simply:
$cat->parent;

echo $parent->title;
like image 83
Jarek Tkaczyk Avatar answered Oct 06 '22 00:10

Jarek Tkaczyk