In: Computer Science
Assuming the correct tables are created for product and manufacturer, describe what needs to be done to specify one-to-many relationship between manufacturer and product in Laravel’s Eloquent.
Ref : https://laravel.com/docs/5.8/eloquent-relationships#one-to-many
A one-to-many relationship is used to define relationships where a single model owns any amount of other models. For example, manufacturer may have an infinite number of products. Like all other Eloquent relationships, one-to-many relationships are defined by placing a function on your Eloquent model: <?php namespace App; use Illuminate\Database Eloquent\Model; class Manufacturer extends Model ** * Get the products for the manufacturer. public function products() return $this->hasMany('App\Product'); Remember, Eloquent will automatically determine the proper foreign key column on the Product model. By convention, Eloquent will take the "snake case" name of the owning model and suffix it with _id. So, for this example, Eloquent will assume the foreign key on the Product model is manufacturer_id.
pnce the relationship has been defined, we can access the collection of products by accessing the products property. Remember, since Eloquent provides "dynamic properties", we can access relationship methods as if they were defined as properties on the model: $products = App\Manufacturer::find(1)->products; foreach ($products as $product) { // Since all relationships also serve as query builders, you can add further constraints to which products are retrieved by calling the products method and continuing to chain conditions onto the query: $product = App\Manufacturer::find(1)->products()->where('title', 'foo')->first(); Like the hasone method, you may also override the foreign and local keys by passing additional arguments to the hasMany method: return $this->hasMany('App\Product', 'foreign_key'); return $this->hasMany('App\Product', 'foreign_key', 'local_key');