laravel5.2.9 - laravel5 model association problem
習慣沉默
習慣沉默 2017-05-16 16:49:37
0
1
554

I now have three tables, as follows

product表的字段为

product_id | product_name | type | price | category
type表的字段为

type_id  |  type_name
category表的字段为

category_id | category_name

Now this is the relationship

The type and category fields in product correspond to the type_id field of the type table and the category_id field of the category table respectively.
How to write the association in the model? In fact, the type and category fields are related to the other two tables in order to obtain to type_name and category_name.

I tried it all night. I don’t know whether it’s one-to-one or one-to-many. I’m so worried. Thanks to my friend for helping me.

習慣沉默
習慣沉默

reply all(1)
阿神
class product extends Model {

    public function type()
    {
        // return $this->hasOne('App\type', 'foreign_key', 'local_key');
        return $this->hasOne('App\type', 'type_id', 'type');
    }
    public function category()
    {
        return $this->hasOne('App\category', 'category_id', 'category');
    }

}
$type = product::find($id)->type;
$category = product::find($id)->category;
$product = product::width('type','category')->get();
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template