Search code examples
laravelrelationships

Linking between 2 tables laravel


I got two tables: "products" and "productPhotos". Each product has an unique id = Product_ID. Each productPhoto has an unique id = ProductPhoto_ID. In my table productPhoto there is also photo and this is specified like so in my migration: $table->binary('photo'); this is for uploading images.

In the table products I've the ProductPhoto_ID(it's a relationship). But how must i add 'photo'?


Solution

  • You need to create the models for each table.

    Also is preferable to use laravel conventions for table/column names.

    So I would call them like this:

    products - id - etc...

    photos - id - product_id - etc...

    Then create 2 models:

        class Product extends Model
        {
            protected $table = 'products';
    
            public function photos()
            {
              return $this->hasMany('App\Photos');
            }
        }
    
        class Photo extends Model
        {
            protected $table = 'photos';
    
            public function product()
            {
              return $this->belongsTo('App\Product','product_id');
            }    
        }
    

    Then in your controllers you'll be fine to get relations like this:

    $product = Product::find($id)->with('photos');

    this will return you a Product model with a property called photos that is a collection of all the Photo models related to it.

    Take a look at https://laravel.com/docs/5.1/eloquent-relationships

    Cheers