$var = categoy[0]['name'];
Get specific columns of relation table
I have 3 tables: categories, subcategories and products. Product table have category_id and subcategory_id as a foreign_key .
I already defined relation in category, subcategory and product Model.
I want to select all products from product table with below conditions:
- Select some columns from
productstable - like id, name, discount, price - select some columns from
categorytable - e.g. id, name - Select some columns from subcategory table - e.g. id, name
$products = Product::with('category:id,name')
->with('subcategory:id,name')
->get()->toArray();
Above code is working fine it is returning custom columns of category and subcategory table as I defined in with method but It also returning all column of product table. Where should I define column of product table?
How should I do this?
@Simbaa you can add an accessor to the Product model:
public function image(): Attribute
{
return new Attribute(get: fn ($image) => asset('storage/'. $image));
}
_If you name the accessor method differently, you can add it to the $appends array so it is serialized with the Model.
public function index ()
{
$products = Product::with('category:id,name')
->with('subcategory:id,name')
->select('id', 'name', 'image', 'discount', 'price', 'category_id', 'subcategory_id')
->paginate();
return Inertia::render('Products/Index', [
'products' => $products
]);
}
You could also consider creating a Eloquent API Resource to design the structure of the JSON representation of the Product instance.
Please or to participate in this conversation.