Retrieving relationships of relationships using Eloquent - laravel

I have a database with the following tables and relationships:
invoice ,order & product
each factor has several orders,and every orders point to a product.
Invoice Model:
class Invoice extends Model
{
public function orders()
{
return $this->hasMany(Order::class);
}
}
Order Model:
class order extends Model
{
public function invoice()
{
return $this->belongsTo(Invoice::class);
}
public function product()
{
return $this->belongsTo('App\Product');
}
}
Product Model:
class product extends Model
{
public function orders()
{
return $this->belongsToMany(Order::class);
}
}
the name of each order is foreign key to the product id,
$table->unsignedBigInteger('name')->references('id')->on('products')->default(0);
in my template i can showing the invoice with orders like this:
{{$invoice->title}}
{{$invoice->client_address}}
#foreach($invoice->orders as $order)
{{$order->name}}
${{$order->price}}
{{$order->qty}}
${{$order->qty * $order->price}}
#endforeach
with this function:
public function show($id)
{
$invoice = Invoice::with('orders')->findOrFail($id);
return view('admin.invoice.show.main', compact('invoice'));
}
how can show the name of product in orders recorde like this:
{{$order->product->name}}
im using before for single loop(e.g., product & category)
but in this example we have 3 relation and using a compact method before.
My product table is:
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('desc');
$table->string('price');
$table->string('image');
$table->string('count');
$table->string('status');
$table->unsignedBigInteger('category_id')->default(0);
$table->foreign('category_id')->references('id')->on('categories');
$table->timestamps();
});

Try this
$invoice = Invoice::with('orders.product')->findOrFail($id);
You can access using something like that
#foreach($invoice->orders as $order)
..
{{ $order->product->name }}
..
#endforeach

I think your relations is wrong...Each product can be within a few orders..so:
Product Model:
class product extends Model
{
public function orders()
{
return $this->belongsToMany('App\Order');
}
}
Order Model:
class order extends Model
{
public function product()
{
return $this->hasOne('App\Product');
}
}
right?
Then access with:
$invoices = Invoice::with('orders.product')->get();

Related

How can i store more than one product_ticket?

Im trying to store more than one product with my controller. In my function store first i generate a ticket and then i generate a product_ticket with the ticket_id recently generated and the product_id from the selected product from the form. But how can i do to store more than one if i select more than one product in the form.
This are my relationships:
Product.php:
class Product extends Model
{
public function tickets()
{
return $this->belongsToMany(Ticket::class);
}
public function productXticket()
{
return $this->hasMany(ProductXTicket::class);
}
}
Ticket.php
class Ticket extends Model
{
public function productXticket()
{
return $this->hasMany(ProductXTicket::class);
}
public function products()
{
return $this->belongsToMany(Product::class);
}
}
ProductXTicket:
class ProductXTicket extends Model
{
protected $table = 'product_ticket';
public function ticket_id(){
return $this->belongsTo(Ticket::class);
}
public function product_id(){
return $this->belongsTo(Product::class);
}
}
product_ticket migration:
Schema::create('product_ticket', function (Blueprint $table) {
$table->id();
$table->foreignId('product_id')->constrained();
$table->foreignId('ticket_id')->constrained();
$table->string('serial_number');
$table->integer('quantity');
$table->timestamps();
});
}
TicketController:
public function store(Request $request){
/*dd($request->all());*/
$ticket = new Ticket();
/*$ticket->cuenta_id = $request->cuenta_id;*/
$ticket->contact_id = $request->contact_id;
$ticket->statusTicket_id = $request->statusTicket_id;
$ticket->typeTicket_id = $request->typeTicket_id;
$ticket->idOwner = Auth::user()->id;
$ticket->save();
$productXticket = new ProductXTicket();
$productXticket->ticket_id = $ticket->id;
$productXticket->serial_number = $request->serial_number;
$productXticket->quantity = $request->quantity;
$ticket->productXticket()->save($productXticket);
Session::flash('success');
return redirect()->route('tickets.view');
}
So here im storing one ticket and one product_ticket. I want form each ticket to store the same amount of product_ticket as the amount products selected
Instead of:
$ticket->productXticket()->save($productXticket);
Use:
$ticket->productXticket()->saveMany([$productXticket,...]);

Reach the subcategory from the Product model (Laravel)

I am trying to reach the last laravel model from the first one with eloquent relationships. How can I reach the Subcategory directly from Product?
The 3 Models I have:
Product (id, category_id, etc..)
public function categories()
{
return $this->belongsTo('App\Category', 'category_id');
}
Category (id, name)
public function products()
{
return $this->hasMany('App\Product', 'category_id');
}
public function sub_categories()
{
return $this->hasMany('App\SubCategory', 'category_id');
}
SubCategory (id, category_id, name)
public function categories()
{
return $this->belongsTo('App\Category', 'category_id');
}
I would've assumed I could reach it with
Product::find(1)->categories->sub_categories;
Am I missing something obvious here?
read this docs
Product
class Product extends Model
{
public function SubCategory()
{
return $this->hasManyThrough('App\Category', 'App\SubCategory');
}
}
In Addition add the subCategories method on Product model and also a product is belongs to a category not categories
and also always try to use camel case for the methods (subCategories)
replace your code with this
Product:
public function category()
{
return $this->belongsTo('App\Category', 'category_id');
}
public function subCategories()
{
return $this->category()->subCategories;
}
Category:
public function products()
{
return $this->hasMany('App\Product', 'category_id');
}
public function subCategories()
{
return $this->hasMany('App\SubCategory', 'category_id');
}
SubCategory:
public function categories()
{
return $this->belongsTo('App\Category', 'category_id');
}
finally use this to get the subcategories
Product::find(1)->subCategories;
Product::find(1)->categories is an array. You will have to loop it to get the subcategory of each category. See below
$categories = Product::find(1)->categories;
foreach ($categories as $category {
//Get subcategories for each category
dump($category->sub_categories);
}

how to many to many relationship query in laravel

Brief:
I use laravel 5.6
I have a problem in many to many relation queries.
I have 2 model: Order and Cart
Code:
Cart Model:
class Cart extends Model
{
public function order()
{
return $this->belongsToMany(Order::class);
}
}
Order model :
class Order extends Model
{
public function carts(){
return $this->belongsToMany(Cart::class);
}
}
Cart Migration :
public function up()
{
Schema::create('carts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->nullable();
$table->integer('price')->nullable();
$table->integer('pass')->default(0);
});
}
Question:
How to get orders that their pass field are in Cart = 1 in?
Thanks!
First, since your Cart has many orders, the relationship should be named "orders" with an s.
You showed only you Cart migration so I cannot guess, but Laravel also expects you to create a "cart-order" pivot table.
If I understood well, you can do what you want like this:
Order::whereHas('carts', function ($query) {
$query->where('pass', 1);
})->get();
You can read more about Eloquent's Many to Many relationships in the Laravel documentation, here.
Try Like this,
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
/**
* Get all of the owning commentable models.
*/
public function commentable()
{
return $this->morphTo();
}
}
class Post extends Model
{
/**
* Get all of the post's comments.
*/
public function comments()
{
return $this->morphMany('App\Comment', 'commentable');
}
}
class Video extends Model
{
/**
* Get all of the video's comments.
*/
public function comments()
{
return $this->morphMany('App\Comment', 'commentable');
}
}
//Access like this in your controller
$post = App\Post::find(1);
foreach ($post->comments as $comment) {
//
}
This Link Help you,
https://laravel.com/docs/5.7/eloquent-relationships#polymorphic-relations in that case. Hope this will help you.

Laravel, make nested SQL query with inner join on Eloquent and Laravel's Models

I have followng database:
Simply speaking, Users have many shops, Shops have many products etc.
I need to make this query with the help of Eloquent ORM:
SELECT * FROM tmp.shops
INNER JOIN
(SELECT * FROM tmp.products
WHERE tmp.products.shop_id IN
(SELECT id FROM shops where user_id = 1)) as nested_query
ON tmp.shops.id = nested_query.shop_id;
I need to catch information about each product in user's shop and info about shop.
About my Models. This is relation with Shop in User model
/**
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function shop()
{
return $this->hasMany('App\Shop');
}
And this is Relations in Shop model:
public function user()
{
return $this->belongsTo('App\User');
}
public function products()
{
return $this->hasMany('App\Product');
}
Finaly, Product model:
public function shop()
{
return $this->belongsTo('App\Shop');
}
Eager load your shop's relation(with('shop')) defined in your product's model as
$user_id=1;
$products = Product::with('shop')
->whereHas('shop.user', function ($query) use($user_id) {
$query->where('id', '=', $user_id);
})
->get();
Models
class Product extends Model {
public function shop() {
return $this->belongsTo('Shop', 'shop_id');
}
}
class Shop extends Model {
public function user() {
return $this->belongsTo('User', 'user_id');
}
public function products() {
return $this->hasMany('Product', 'shop_id');
}
}
Now when you iterate products you will get shop details object in each product object

laravel 5 many to many not working

I have a many to many relationship between Products and Categories Table with Pivot table as Product_Category
In Products Model:
public function categories(){
return $this->belongsToMany('\App\Models\Categories', 'product_category', 'product_id', 'category_id');
}
In Categories Model:
public function products(){
return $this->belongsToMany('\App\Models\Products', 'product_category', 'category_id', 'product_id');
}
In Product_Category Model:
public function products(){
return $this->belongsTo('App\Models\Products');
}
public function categories() {
return $this->belongsTo('App\Models\Categories');
}
In ProductController:
$data = Products::with('categories')->select('id','product_name','user_id','created_at')->orderBy('id', 'desc')->paginate(20);
Then i test with function below:
foreach ($data as $val) {
$cats = $val['categories'];
}
I try to var_dump(), but nothing happened:
object(Illuminate\Database\Eloquent\Collection)#472 (1) {
["items":protected]=> array(0) { }
}
Please help me
When you have created a Pivot Model in your application, then This pivot table has a one-to-many relationship with each of your corresponding models. i.e. Product_Category model has a one-to-many relationship with Products and Categories Models. So, code in Products and Categories Models will be like below:
In Products Model:
public function categories(){
return $this->hasMany('\App\Models\ProductCategory', 'category_id');
}
In Categories Model:
public function products(){
return $this->hasMany('\App\Models\ProductCategory','product_id');
}
Do the changes as above and it should be working.

Resources