Laravel hasManyThrough return nothing - php

Products:
-----------------------
|id | name | seller_id |
-----------------------
| 1 | bmw | 1 |
-----------------------
| 2 | benz | 1 |
-----------------------
| 2 | reno | 2 |
-----------------------
Buy:
------------------------------
|id | product_id | buyer_id |
------------------------------
| 1 | 1 | 1 |
------------------------------
| 2 | 1 | 2 |
------------------------------
| 3 | 2 | 22 |
------------------------------
Buyer:
------------------------------
|id | name | email |
------------------------------
| 1 | john | # |
------------------------------
| 2 | mike | # |
------------------------------
| 3 | dave | # |
------------------------------
Explaination:
Seller products store in products table, after buyer bought products, it store in buy table. there are buyer table and also seller table, what I want to do is, show those buyer data to seller who has bought seller products.
Consider, a seller with seller_id 1, made products, some buyers bought his/her products, right? now I want to show to seller, who bought your products. john and mike bought bmw, now seller with id 1 should see mike and john email and etc under each products.
What I tried:
ProductController.php:
$pro = Product::where('seller_id', $seller->id)->where('deleted', 0)->with('buyer')->get();
Product.php:
function buyer()
{
//return $this->belongsTo('App\Buy', 'id'); // this just show me buyer_id
return $this->hasManyThrough('App\Buyer', 'App\Buy', 'id', 'id', 'product_id', 'buyer_id');
}
This return me products but buyer is empty "buyer": [], I'm new to laravel, I don't know which localKey, firstKey, secondKey or secondLocalKey related to which table. So any idea what I have done wrong?
-- Edit --
public function userproducts()
{
$seller = Auth::seller();
$pro = Product::where('seller_id', $seller->id)->where('deleted', 0)->with('buyer')->get();
return response()->json($pro, 200 );
}

You're making the wrong relationship. As you explain your Product has many buyers and the buyer can purchase many Products.
So, It'll be a Many-to-Many Relationship.
Try to make relationship as below and then check it'll work for you.
Product.php Model
function buyers(){
return $this->belongsToMany('App\Buyer','Buy_table_name','product_id','buyer_id');
}
In Buyer.php Model
function products(){
return $this->belongsToMany('App\Product','Buy_table_name','buyer_id','product_id');
}
Now, use this query in controller file.
$pro = Product::where('seller_id', $seller->id)->where('deleted', 0)->with('buyers')->get();

Related

codeigniter query: how to take all the record from a column in a table when i use sum Select function to get data from another table

the case is i have this table called journal_type
id_type | account_no | description |
---------------------------------------------
1 |
1.1 |
bank
2 |
1.2 |
bank & cash
3 |
1.3 |
sale
4 |
1.4 |
stock
5 |
1.5 |
office tools
6 |
1.6 | payroll
and the second table called journal is something like this
id_transaction | id_type | debit | date_of_transaction
---------------------------------------------
1 |
1 |
50.00 | 08-22-2018
2 |
3 |
90.00 | 08-21-2018
3 |
1 |
80.00 | 08-17-2018
what i do so far is sum the data from second table's debit column based on month(in this case is august) and i want to group it by the id_type. so it would be something like id_type1 = 130.00 and id_type3 = 90.00
but i want the output is printing all the record from the id_type column in first table and let the other column null when it don't used. maybe the result i want is something like this
id_type | account_no | description | debit
---------------------------------------------
1 |
1.1 |
bank | 130
2 |
1.2 |
bank & cash| 0
3 |
1.3 |
sale | 90
4 |
1.4 |
stock | 0
5 |
1.5 |
office tools |0
6 |
1.6 | payroll | 0
public function get_finance_debitkredit($periode1, $periode2){
$query = $this->db->select('sum(debit) as debit, journal_type.account_no, journal_type.description, journal.id_type')
->from('journal_type')
->join('journal', 'journal.id_type = journal_type.id_type', 'left outer')
->group_by('journal.id_type')
->where('date_of_transaction >=', $periode1)
->where('date_of_transaction <=', $periode2)
->order_by('journal_type.account_no')
->get();
return $query;
}
but so far what I get is that it's only printed the record data that have the transaction (in this case is the id_type 1 and id_type_3) so only 2 row that appear. can i make all the 6 row of journal_type appear like what i want with some change of the query.
that code is from my model in codeigniter
You first need to create seperate table for that records and then need to left join with that table. Use following query it will give the result you want
public function get_finance_debitkredit($periode1, $periode2){
$query = $this->db->select('finl_tbl.debit, journal_type.account_no, journal_type.description, journal_type.id_type')
->from('journal_type')
->join('(SELECT sum(debit) as debit,id_type FROM journal WHERE date_of_transaction >='.$periode1.' AND date_of_transaction <='.$periode2.' group by id_type) as finl_tbl', 'finl_tbl.id_type = journal_type.id_type', 'left')
->order_by('journal_type.account_no')
->get();
return $query;
}

How can I write a relation for pivot table in Laravel?

Here is my table structure:
// tickets
+----+------------+----------------------+--------+---------+-------------------+
| id | subject | content | closed | user_id | unique_product_id |
+----+------------+----------------------+--------+---------+-------------------+
| 1 | subject1 | question1 | 0 | 123 | 2 |
+----+------------+----------------------+--------+---------+-------------------+
// unique_product
+----+---------------+------------+
| id | serial_number | product_id |
+----+---------------+------------+
| 1 | 2342rd34fc | 3 |
| 2 | fg34gt4r5t | 1 |
| 3 | 34ffvv4et6 | 3 |
+----+---------------+------------+
// products
+----+--------------+
| id | name |
+----+--------------+
| 1 | Router-rb51 |
| 2 | Switch-sfx2 |
| 3 | Router-rb300 |
+----+--------------+
Now I have a collection of tickets like this:
$tickets = tickets::where(user_id, "$user_id")->get();
foreach( $tickets as $ticket ){
$ticket->{I need to get the name of product here}
}
I can write a relation in the tickets model like this:
public function unique_product()
{
return $this->hasOne(unique_product::class, 'id', 'unique_product_id');
}
And I need one more relation to the products table for getting the name of product (i.e. Switch-sfx2). How should I write that relation?
$tickets = tickets::where(user_id, "$user_id")->with('unique_product.product')->get();
You can take advantage eager loading using with().
but for using with('unique_product.product') You have to define the relation ships between unique_products and products.
In your UniqueProduct model create a new relationship
public function product()
{
return $this->BelongsTo(Product::class, 'id', 'product_id');
}
After that you can access the column of a name like
foreach( $tickets as $ticket ){
$ticket->unique_product->product->name
}

Laravel Eloquent multiple relationship in a football game schedule

I am new to Laravel and Eloquent and i am trying to create a football game plan.
For now i have 4 tables (with some example entries):
teams (all teams)
+---------+-----------+
| team_id | team_name |
+---------+-----------+
| 1 | Arsenal |
| 2 | Chelsea |
+---------+-----------+
competition (all competitions)
+----------------+------------------+
| competition_id | competition_name |
+----------------+------------------+
| 1 | Premier League |
+----------------+------------------+
schedule (schedule to the competitions)
+----+----------------+----------+--------------+--------------+-----------+-----------+
| id | competition_id | matchday | home_team_id | away_team_id | home_goal | away_goal |
+----+----------------+----------+--------------+--------------+-----------+-----------+
| 1 | 1 | 1 | 1 | 2 | 3 | 2 |
| 2 | 1 | 2 | 2 | 1 | 0 | 3 |
+----+----------------+----------+--------------+--------------+-----------+-----------+
schedule_teams (matches the schedule teamid with the teams id over the competition_id and the schedule_team_id)
+----+------------------+----------------+----------+
| id | schedule_team_id | competition_id | teams_id |
+----+------------------+----------------+----------+
| 1 | 1 | 1 | 1 |
| 2 | 2 | 1 | 2 |
+----+------------------+----------------+----------+
And here are my current classes:
Schedule.php
public function competition()
{
return $this->belongsTo(Competition::class, 'competition_id', 'competition_id');
}
Competition.php
public function schedule()
{
return $this->hasMany(Schedule::class, 'competition_id', 'competition_id');
}
With
$id = \request('competition_id');
$schedule = Schedule::where('competition_id', $id)->with('competition')->get();
i get the schedule with the home and away id's from schedule.
The question now is, how can i get the entries from the teams table over the schedule_teams table to a specifiy home and away id, also for example home_team_id = 1:
home_team_id (=1) -> schedule_team_id (=1) and competition_id (=1) -> teams (Arsenal)
I want the data from schedule and the associated teams in a collection to output in a blade.
can anyone help or give me improvement tips for a football database?
You should make use of the hasManyThrough relationship.
If you create say Schedule\Team, and then have that like the following.
public function schedule() {
$this->belongsTo(Schedule::class, 'schedule_id');
}
public function team() {
$this->belongsTo(Team::class, 'team_id');
}
Now in your Schedule class, you can have the following.
public function teams() {
$this->hasManyThrough(Team::class, Schedule\Team::class, 'schedule_id');
}
It should also be noted, that you don't need competition_id in your schedule team. Since a team belongs to a schedule, which belongs to competition, you can get it like that.
If you also want your Team to know about its schedules, you can add this to Team.
public function schedules() {
return $this->hasManyThrough(Schedule::class, Schedule\Team::class);
}
You Schedule\Team class becomes essentially, a glorified representation of a pivot table, but having it as a model, allows you to expand upon it in the future. It also helps keep everything neat.
Hope that makes sense.

$this->db->group_by() and adding the quantity

I have this in my receipt UI(Note: This is only from one user):
Item_Name | Quantity | Price | Total
Panty | 2 | 50 | 100
Bra | 1 | 35 | 35
Panty | 2 | 50 | 100
As you can see the user gets the Panty TWICE!
I want my UI to be looking like this:
Item_Name | Quantity | Price | Total
Panty | 4 | 50 | 100
Bra | 1 | 35 | 35
As you can see the Panty's that the user buys groups together, but in my query instead of Panty having 4 Quantity it still has 2
Here is my Code:
public function getClientReservation($name){
$this->db->select('*');
$this->db->from('tbl_item_availed');
$this->db->join('tbl_items','tbl_items.Item_ID = tbl_item_availed.Item_ID');
$this->db->join('user_account','user_account.Account_no = tbl_item_availed.Account_no');
$this->db->where('Username',$name);
$this->db->where('isReserve',1);
$this->db->where('Active',1);
$this->db->group_by('tbl_items.Item_Name');
$query = $this->db->get();
return $query->result();
}
Please help!
This is the table tbl_item_availed by the way:
Item_availed_id | Item_ID | Quantity | Account_no
1 | 1 | 2 | 5
2 | 2 | 1 | 5
3 | 1 | 2 | 5
table tbl_items:
Item_ID | Price | Item_Name
1 | 100 | Panty
2 | 35 | Bra
table user_account:
Account_no | Firstname | Lastname
1 | LeBron | James
2 | Dwyane | Wade
3 | Wilt | Chamberlain
4 | Michael | Jordan
5 | Charles | Barkley
Try this.
public function getClientReservation($name){
$this->db->select('tbl_items.`Item_Name`, SUM(tbl_item_availed.`Quantity`) AS quantity, tbl_items.`Price`, (tbl_items.`Price`*(SUM(tbl_item_availed.`Quantity`))) AS total');
$this->db->from('tbl_item_availed');
$this->db->join('tbl_items','tbl_items.Item_ID = tbl_item_availed.Item_ID');
$this->db->join('user_account','user_account.Account_no = tbl_item_availed.Account_no');
$this->db->where('Username',$name);
$this->db->where('isReserve',1);
$this->db->where('Active',1);
//$this->db->group_by('tbl_items.Item_Name');//do not use this line unless item name is unique
//group by item id
$this->db->group_by('tbl_items.Item_ID');
$query = $this->db->get();
return $query->result();
}
Also use GROUP BY for Item_ID (assuming it is unique), not Item_Name unless it is unique.
Side note:
Moreover, use Account_no instead of username in WHERE clause. If you want to modify it, just replace this line
$this->db->where('Username',$name);
with
$this->db->where('Account_no',$account_no);

Laravel getting results from model belongsToMany relationship back to controller

I'm using Laravel 5 and Eloquent, I have 3 tables setup:
photos
+----+---------------+------------------+
| id | photo_name | photo_location |
+----+---------------+------------------+
| 1 | kittens.jpg | C:\kittens.jpg |
| 2 | puppies.jpg | C:\puppies.jpg |
| 3 | airplanes.jpg | C:\airplanes.jpg |
| 4 | trains.jpg | C:\trains.jpg |
+----+---------------+------------------+
photo_set (pivot table)
+------------+----------+
| set_id | photo_id |
+------------+----------+
| 1 | 1 |
| 1 | 2 |
| 2 | 3 |
| 2 | 4 |
+------------+----------+
sets
+----+----------------+
| id | description |
+----+----------------+
| 1 | cute animals |
| 2 | transportation |
+----+----------------+
I created a belongsToMany relationship in my photos and sets models to link these two together.
class Photo extends Model {
public function sets()
{
return $this->belongsToMany('App\Set');
}
}
and
class Set extends Model {
public function photos()
{
return $this->belongsToMany('App\Photo');
}
}
However I'm trying to reference the $Sets->photos() model function in my controller, so that given a set of id=1, I can return the photo_location value for each row [C:\kittens.jpg,C:\puppies.jpg], but I don't know how to access it..
Also, I can "sort of" access this information in the view with:
#foreach($sets as $set)
{{$set->images}}
#endforeach
but it looks like it only iterates through once and returns a json (?) of the necessary information, though I'm not sure how to parse that to regular HTML either.
So in short, I'm having trouble accessing this data (photo_location) from both the controller and the view
Use Collection::lists()
$locations = Set::find(1)->photos->lists('photo_location');
It will return an array ['C:\kittens.jpg', 'C:\puppies.jpg']
http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_lists
In your controller try this :
$result = PhotoSet::where('set_id', $set_id)
->with('sets')
->with('photos')
->get();
$photo_location = $result->photos->photo_location;
here PhotoSet is the model for photo_set table, because it is a pivot table we will be able to access both sets and photos table from it.

Categories