mercredi 15 janvier 2020

how to access data of table having two foreign keys in laravel

i have a table called order_details which is having two foreign keys. (1.) order_id (2.) product_id

i have compacted the whole table in my view. when i access the records related to order they are working well but when i try to access the record of products which are foreign as product_id in order_detail table i am getting null.

Table of OrderDetails:

Schema::create('order_details', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('order_id');
            $table->foreign('order_id')->references('id')->on('orders');
            $table->unsignedBigInteger('product_id');
            $table->foreign('product_id')->references('id')->on('products');
            $table->integer('quantity');
            $table->integer('amount');

            $table->timestamps();
        });

Model of OrderDetail:

 public function order(){
        return $this->belongsTo(Order::class);
    }
    public function products(){
        return $this->hasMany(Product::class);
    }

Model of Order:

 public function orderDetails(){
        return $this->hasMany(OrderDetail::class);
    }

Model of Product:

 public function orderDetail(){
        return $this->belongsTo(OrderDetail::class);
    }

i have compacted the whole table in $orderDetails on my view. when i try to access data of Order table like this:

$orderDetails[0]->Order['total_ammount']

its working fine as it is accessing the order model through order_id. but with the same way i try to get data from Product Model using product_id like this

$orderDetails[0]->Product['name']

its showing me no error but null.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2uIhslB
via IFTTT

Aucun commentaire:

Enregistrer un commentaire