Laravel 3 Table Relationship - php

Can anyone help me how to display the product name? I have productquantity stored in my purchase record and now I want to display the product name in productquantity record.
I have 3 Tables
Purchaserecord
id
purchasenumber
prodquantityid
Productquantities
id
prod_id
Product
id
productname
Controller:
public function createpurchase(Request $request)
{
$purchasenumber = $request->purchasenumber;
$dataPurchaseRecord = Purchaserecord::where('purchasenumber','=',$purchasenumber)->with('productquantity')->get();
return view('admin.createpurchase',compact('purchasenumber', 'dataPurchaseRecord'));
}
View:
#forelse($dataPurchaseRecord as $Request)
<tr>
<td> <a class="name">{{$Request->productquantity->prod_id}}</a></td>
<td><em class="productprice">{{$Request->quantity}}</em> </td>
<td style="width:100px;" class="td-actions"> </i>Remove </td>
</tr>
#empty
<tr><td colspan='4'><em>No Data</em></td></tr>
#endforelse
Model:
public function product()
{
return $this->belongsTO('App\Product', 'prodquantityid', 'id');
}
{{$Request->productquantity->prod_id}} should be display the product name instead of the id
How can I build the model and view on this?

You could define your models as
Class Purchaserecord extends Model{
public function productquantity()
{
return $this->belongsTo('App\Productquantities', 'prodquantityid');
}
}
Class Productquantities extends Model{
public function product()
{
return $this->belongsTo('App\Product', 'prod_id');
}
public function purchaserecords()
{
return $this->hasMany('App\Productquantities','prod_id');
}
}
Class Product extends Model{
public function productquantities()
{
return $this->hasMany('App\Productquantities','prod_id');
}
}
Now eager load your data like
$dataPurchaseRecord = Purchaserecord::where('purchasenumber','=',$purchasenumber)
->with('productquantity.product')
->get();
In loop you access product object as $Request->productquantity->product->name
Eloquent: Relationships

Related

How to use hasMany which has belongsTo in the child

I have database relation like below
I want to get shop data with their products which each product has their category. If we define it using Eloquent ORM in Laravel, shop hasMany products belongsTo productCategory.
I can get the data of shop with their products using hasMany, but I can't get the productCategory of each products. Does anyone know how to get the productCategory of each product?
Shop model:
class Shop extends Model
{
public function products() {
return $this->hasMany('App\Product');
}
}
Procuct model:
class Product extends Model
{
public function shop() {
return $this->belongsTo('App\Shop');
}
public function category() {
return $this->belongsTo('App\ProductCategory');
}
}
Product category model:
class ProductCategory extends Model
{
public function products() {
return $this->hasMany('App\Product');
}
}
Shop controller to get the data:
class ShopController extends Controller
{
public function show(Shop $shop)
{
$products = $shop->products()->get();
return view('pages.shop-detail.index')->with('shop', $shop)->with('products', $products);
}
}
On One To Many (Inverse) Relationships:
Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with a _ followed by the name of the primary key column. However, if the foreign key on the Product model is not category_id, you should pass the custom key name as the second argument to the belongsTo method:
class Product extends Model
{
public function category() {
return $this->belongsTo('App\ProductCategory', 'product_category_id');
}
}
Then in the view, loop over shop products an show the name of the product and the name of the product category:
<h3>Shop: {{ $shop->name }}</h3>
#foreach ($shop->products as $product)
<p>Product: {{ $product->name }}</p>
<small>Category: {{ $product->category->name }}</small>
#endforeach
But...
Doing the query in the way you had it in the question you'll have an N + 1 problem when you loop on products in the view.
Avoid the model binding in your controller to eager load the relationships and return just the shop, the products and category will be eager loaded on the Shop object:
class ShopController extends Controller
{
public function show($id)
{
$shop = Shop::with('products', 'products.category')->find($id);
return view('pages.shop-detail.index')->with('shop', $shop);
}
}

call relation in accessor function

I want to call relation into accessors function with less query
ticket has many messages
ticket model has accessors function
I want into accessors function if ticket->messages()->exist() == TRUE returns messages body, or ** if ticket->messages()->exist() == TRUE** returns tickets body
this line code ($ticket->last_body) in view make one Query for each row and i want to decrease my query
Ticket model:
class Ticket extends Model
{
public function messages()
{
return $this->hasMany(TicketMessage::class, 'ticket_id');
}
public function getLastBodyAttribute()
{
if($this->messages()->exists()){
return $this->messages()->orderByDesc('created_at')->first()->body;
} else {
return $this->body;
}
}
}
Ticket massage belongsto tickets
TicketMessage model :
class TicketMessage extends Model
{
public function ticket()
{
return $this->belongsTo(Ticket::class,'ticket_id');
}
}
I get tickets with own relationships and passed to view
TicketController:
class TicketController extends Controller
{
public function index(Request $request)
{
$tickets = Ticket::with('messages')
->where('status', 'open')
->get();
return view('ticket::supporter.supporter', compact('tickets'));
}
}
this line code $ticket->last_body make one Query for each row and i want to decrease my query
**supporter.blade** :
#foreach($tickets as $ticket)
<a href="{{url(Route('show_client_ticket', ['id' => $ticket->id]))}}">
{{$ticket->subject}}
</a>
<p style="color: #959A9D;">
{{$ticket->last_body}} //this line returns too much Query
</p>
<hr>
#endforeach
Try to change this.
public function ticket()
{
return $this->belongsTo(Ticket::class,'ticket_id');
}
to this.
public function ticket()
{
return $this->belongsTo(Ticket::class,'id');
}
because the default primary key of the model is "id".
or if you want to change the primary key. try this:
class Ticket extends Model
{
protected $primaryKey = 'ticket_id';
...

How can I connect one to many relationship in laravel eloquent?

Image model:
public function getImage(){
return $this->belongsTo('App\Product');
}
Product model:
public function product(){
return $this->hasMany('App\Image');
}
Controller:
public function index()
{
$products = Product::all(); //Select *
return view('product.index',compact('products'));
}
View:
#foreach($products as $product)
<td>{{ $product->getImage->image_link}}</td>
#endforeach
Error:
Trying to get property 'image_link' of non-object (View:
C:\xampp\htdocs\ecommerce\resources\views\product\index.blade.php)
Their should be a relation between post and product with product id
In Product.php
public function product(){
return $this->hasMany('App\Image');
}
then you can use $product->images->image_link
Is there a product_id field in your image table? and is there hasMany in your Product model?
In your Product model should be a relation like as below.
Product.php
public function images(){
return $this->hasMany('App\Image');
}
After then, you can use images in product for loop $product->images->image_link.

Can't display data in view from model in Laravel

In my project I have orders which have many products and customers who have many orders. I am confused because I want to get all orders that a certain customer has and the products of each order. I messed up something somewhere and I am not sure if I set my relationships correctly. Here is my products table:
Here is my customers table:
And here is my orders table:
Here are my models:
Product:
class Product extends Model
{
public function orders()
{
return $this->belongsToMany('App\Order');
}
}
Order:
class Order extends Model
{
public function products()
{
return $this->hasMany('App\Product', 'id');
}
public function customer()
{
return $this->belongsTo('App\Customer');
}
}
Customer:
class Customer extends Model
{
public function orders()
{
return $this->hasMany('App\Order', 'id');
}
}
I get all customers from my database with App\Customer::all() in my CustomersController and pass the data in my customers.blade.php.
<h1>Customers:</h1>
#foreach($customers as $customer)
<h3>{{$customer->name}}</h3>
#foreach($customer->orders as $order)
<p>Order ID: {{$order->id}}</p>
#foreach($order->products as $product)
<p>Product title: {{$product->title}}</p>
#endforeach
#endforeach
<hr>
#endforeach
Here is the output:
If someone could explain why it doesn't output everything and give some advice if this is the way to go with the relationships, I would be very thankful.
Your products should belong to an order, rather than have a many-to-many relationship.
class Product extends Model
{
public function orders()
{
return $this->belongsTo('App\Order');
}
}
I found a solution by making a pivot table for products and orders called products_orders which holds the product_id and the order_id and making a many to many relationship between Product and Order. That is because an order may have multiple products and products may exist in multiple orders.
My pivot table products_orders:
class Product extends Model
{
public function orders()
{
return $this->belongsToMany('App\Order');
}
}
class Order extends Model
{
public function products()
{
return $this->belongsToMany('App\Product', 'products_orders');
}
public function customer()
{
return $this->belongsTo('App\Customer');
}
}
I made a one to many relationship (customer_id in orders table) for Customer and Order and now everything works fine.
class Customer extends Model
{
public function orders()
{
return $this->hasMany('App\Order');
}
}

How do display a variable from a databse with through Relational Models?

I have a list of books and a list of authors. I made the Model relations, so that my Book Model says, that books->belongTo('Author') and my Author Model says, that authors->hasMany('Book').
So normally I could access the a variable through this:
$books = Book::all();
And then in the view:
#foreach($books as $book)
<div>{{$book->id}}</div>
<div>{{$book->title}}</div>
<div>{{$book->authors->firstname}}</div>
#endforeach
But this does not work. I get the error message: Trying to get property of non-object
So here are my files:
My Models:
Book.php
class Book extends \Eloquent {
protected $guarded = [];
public function religions()
{
return $this->belongsTo('Religion');
}
public function branches()
{
return $this->belongsTo('Branch');
}
public function authors()
{
return $this->belongsTo('Author');
}
public function quotes()
{
return $this->hasMany('Quote');
}
public function chapters()
{
return $this->hasMany('Chapter');
}
}
Author.php
class Author extends \Eloquent {
protected $guarded = [];
public function books()
{
return $this->hasMany('Book');
}
public function quotes()
{
return $this->hasMany('Quote');
}
public function branches()
{
return $this->belongsTo('Branch');
}
public function religions()
{
return $this->belongsTo('Religion');
}
}
Then come my controller:
ReligionBranchBookController
class ReligionBranchBookController extends \BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index($religionId, $branchId)
{
//
// $books = Book::where('religion_id', $religionId)->where('branch_id', $branchId)->get();
$books = Book::all();
$authors = Author::all();
// dd($books->toArray());
return View::make('books.index')
->with('religionId', $religionId)
->with('branchId', $branchId)
->with('books', $books)
->with('authors', $authors);
}
}
My Views:
index.blade.php
#extends('layout.main')
#section('content')
<h1>Books List!!</h1>
<table>
<tr>
<th>ID</th>
<th>Title</th>
<th>Author</th>
</tr>
#foreach($books as $book)
<tr>
<td>{{$book->id}}</td>
<td>{{$book->title}}</td>
<td>{{$book->authors->firstname}}</td>
</tr>
#endforeach
</table>
#stop
I know that it should normally work, I rebuild it with only books and authors, and it works fine there.
So, does anyone have an idea, where I am going wrong?
Thanks,
George
In your Book model change the authors method to author like this:
public function author()
{
return $this->belongsTo('Author');
}
Because, one book belongs to one author according to your relationship and when you call authors the belongsTo->getResults() get called and runs the wrong query so authors get null and you get the error. Things to remember:
For hasOne and belongsTo relationship use singular form of relationship method, i.e, author not authors.
hasOne or belongsTo returns a single model object.
For hasMany and belongsToMany relationship use plural form of relationship method, i.e, authors not author.
hasMany and belongsToMany returns a collection of model objects.

Categories