Search code examples
mysqllaravelnested

how to use inside mysql with laravel if for each product supported languages with some nested supported info ... see to understand


am using laravel with (mysql)... what i want to do is same like this:

for each product->>>
       langs 
          english:
             interface: true,
             subtitles: false,
             interface: true,
          ,
          arabic:
             interface: false,
             subtitles: true,
             interface: true,
          ,
          .........
          .........

but with... ( Each language has its own products, such as one tag or else )

am expecting to get each product with supported langs with this example above about nested info for each lang row

Please be clear in your response with ( laravel or mysql or any tool make the idea clear


Solution

  • Language Model

    class Language extends Model
    {
        public function products()
        {
            return $this->belongsToMany(Product::class, 'language_product')
                ->withPivot('interface', 'subtitles');
        }
    }
    

    Product Model

    class Product extends Model
    {
        public function languages()
        {
            return $this->belongsToMany(Language::class, 'language_product')
                ->withPivot('interface', 'subtitles');
        }
    }
    

    your pivot table language_product will have the product id and language id and the other fields like interface, subtitles, etc. and you can fetch it withPivot in the relationship

    You can now retrieve each product with its supported languages.

    $products = Product::with('languages')->get();
    
    foreach ($products as $product) {
      
       foreach ($product->languages as $language) {
           
       }
    }
    

    you can read more from here official docs