I want to loop through with all main categories. This is to use where-condition to check which categories have the id on main category and output it.
The DB look like this:
id | name | parent_ids
10 | Cat1 |
12 | Cat3 |
17 | Cat2 | 10,12
25 | Cat4 | 12
#foreach($lagerMainCategories-\>where('parent_ids', $lagerMainCategory-\>id) AS $lagerSubCategories)
<li>
{{$lagerSubCategories-\>name}} ({{$lagerSubCategories-\>id}})</li>
#include('Skote.layouts.lagerCategory.lagerSubCategory', \['lagerMainCategory' =\> $lagerSubCategories\])
#endforeach
I get out
Cat1
Cat3
Cat4
I want to
Cat1
Cat2
Cat3
Cat2
Cat4
Ok, thanks for Help. I have found a solution.
#foreach($lagerMainCategories->where('parent_ids', '!=', null) AS $lagerSubCategories)
#if(in_array($lagerMainCategory->id, explode(',', $lagerSubCategories->parent_ids)))
<li>{{$lagerSubCategories->name}} ({{$lagerSubCategories->id}}) </li>
#include('Skote.layouts.lagerCategory.lagerSubCategory', ['lagerMainCategory' => $lagerSubCategories])
#endif
#endforeach
Related
I'm new in laravel and I need help with this. So I have 3 different table as shown below. I have to calculate the quantity of item based on the different value in the two tables. First, I have to get the sum of the value table 1 and table 2 and group it by the item. After that minus the result and display in item table in my blade by the quantity column
Item table
|ID | Item | quantity |
+---+---------+-------------+
|1 | item1 | |
|2 | item2 | |
|3 | item3 | |
|4 | item4 | |
Value1 table
|ID | Item | value |
+---+---------+-------------+
|1 | item1 | 4757.34 |
|2 | item1 | 938.00 |
|3 | item1 | 0.00 |
|4 | item2 | 6574.3 |
|5 | item2 | 74.40 |
Value2 table
|ID | Item | value |
+---+---------+-------------+
|1 | item1 | 27.64 |
|2 | item1 | 0.00 |
|3 | item1 | 2.00 |
|4 | item2 | 64.34 |
|5 | item2 | 4.40 |
This is what I have done so far
My Eloquent
public function getValue1()
{
$query = Value1::select(DB::raw("SUM(value) as value1"))
->groupBy('item')
->get();
return $query;
}
public function getValue2()
{
$query = Value2::select(DB::raw("SUM(value) as value2"))
->groupBy('item')
->get();
return $query;
}
My Controller
$value1 = $myEloquentRepo->getValue1();
$value2 = $myEloquentRepo->getValue2();
$quantity = $value1 - $value2;
But it seems like I'm not doing it correctly as I got an error Object of class Illuminate\Database\Eloquent\Collection could not be converted to number. Any guide will be appreciated.
That is much simpler to be done with plain SQL. It will be much faster for the server as there will be 3 times less requests to the database.
$query = "INSERT into ItemTable
SELECT t1.item, (t1.qty - t2.qty) as 'quantity'
from (
select Item, sum(value) 'qty'
from table1
group by Item
) t1
join (
select Item, sum(value) 'qty'
from table2
group by Item
) t2 on t1.Item = t2.Item
";
DB::uprepared($query);
the SELECT query itself will return you the needed result. Then based whether your ItemTable is empty or filled, you insert or update into it.
I have 4 tables named: categories, products, blogs, companies.
+-----------+
| Category |
+----+------+
| id | name |
+----+------+
| 1 | Cat1 |
| 2 | Cat2 |
+----+------+
+-----------+
| Company |
+----+------+
| id | name |
+----+------+
| | |
+----+------+
+-------------------------+
| Product |
+----+-------------+------+
| id | category_id | name |
+----+-------------+------+
| 1 | 1 | P1 |
| 2 | 2 | P2 |
| 3 | 1 | P3 |
+----+-------------+------+
+---------------------------+
| Blog |
+----+------------+---------+
| id | product_id | heading |
+----+------------+---------+
| 1 | 1 | H1 |
| 2 | 2 | H3 |
| 3 | 3 | H4 |
+----+------------+---------+
Blog Model
public function product()
{
return $this->belongsTo(Product::class);
}
Product Model
public function company()
{
return $this->belongsTo(Company::class);
}
public function category()
{
return $this->belongsTo(Category::class);
}
Blog::with('product.category')
->where('status', 'Y')
->where('featured_position', 'Y')
->orderBy('id', 'DESC')
->get();
From the above tables the result will show 2 blogs namely blogs having id 1 and 3. But the above code is fetching result for all the blogs from the blog table.
You'll want to use a whereHas to query the relationship.
$categoryId = 1;
$productQuery = function ($query) use ($categoryId) {
// This $query object will be for the Product models, so we can treat it as
// such.
// We can query like we would on a Product, like Product::where([...]).
$query->with('category')->where('category_id', $categoryId);
};
$blogs = Blog::whereHas('product', $productQuery)
->with(['product' => $productQuery])
->get();
I've set the category ID to a variable, in case you need to change it during runtime.
Also, note that the with is completely optional.
If you exclude it, your query will run exactly the same, just without constrained eager loading. The effects of this are just that you will have to perform more database requests. The benefits come if you never actually need the relationship, then it won't have been fetch unnecessarily.
If you're curious what the SQL command will be, it will be:
SELECT * FROM `blogs`
WHERE EXISTS (
SELECT * FROM `products`
WHERE `blogs`.`product_id` = `products`.`id` AND `category_id` = ?
)
In simple terms, it will select everything from the blogs table.
It's then going to query the products table, using an inner join, to select products that have a corresponding blog entry.
The second part of the where clause is going to just get the specific character. The ? is because category_id can be any integer.
Catory with id 1
fetch its products
fetch blogs for each of its products ( map over products )
flatten the results ( since its gonna be nested for each product )
Category::find(1)->products->map->blogs->flatten();
you can use Tinker to interact with you application's query builder and eloquent models from terminal you can use :
$ php artisan tinker
For more clause you can use collection methods :
Category::find(1)->products->map->blogs->flatten()->where('status', 'Y')
->where('featured_position', 'Y')
->sortDesc('id') ;
I want to show product sizes related to product I already have made a relation b/w tables into database i just only want to know that when i click the specific product the size related to that product will be shown in the table.inside function how to make joining b/w three tables please make the join table using DB class because it will be easy to understand for me thanks.
Does Anyone have an idea ?
please check product sizes image
https://i.stack.imgur.com/Yt6Jk.png
Database
product_sizes table
----------------------------------------------------
id | size_name | Body_length | Body_width |
----------------------------------------------------
1 | M | 2.3 | 3.4
2 | L | .5 | 4.4
3 | s | 2.5 | 3.2
4 | xs | 3.5 | 2.4
products table
----------------------------------------
id | product_name | Description |
----------------------------------------
1 Ultraclub 1 | Ultraclub 300 |
2 Ultraclub 2 | Ultraclub 200 |
3 Ultraclub 3 | Ultraclub 500 |
4 Ultraclub 4 | Ultraclub 600 |
5 Ultraclub 5 | Ultraclub 400 |
available_product_sizes table
----------------------------------------
id | product_id | product_size_id
----------------------------------------
1 | 2 | 1
2 | 3 | 4
3 | 4 | 3
4 | 1 | 2
5 | 2 | 3
Controller
public function single_product($product_slug){
$Sizes=DB::table('product_sizes')->get();
$single_product=DB::table('products')->where('product_slug',$product_slug)->get();
return view('front_end/single_product',compact('single_product','Sizes'));
}
html view
<div class="product-tabs__pane product-tabs__pane--active" id="chart">
<table class="table table-bordered text-center">
<tr style="background-color:#3366cc;color:white">
<td><b>Sizes</b>
</td>
<td><b>Body length</b>
</td>
<td><b>Body width</b>
</td>
<td><b>Sleeve length</b>
</td>
</tr>
#foreach($Sizes as $size)
<tr>
<td><b>{{$size->sizes_name}}</b>
</td>
<td>{{$size->Body_length}}</td>
<td>{{$size->Body_width}}</td>
<td>{{$size->Sleeve_length}}</td>
</tr>
#endforeach
</table>
</div>
I assume you're already has/desfined many-to-many relationship between products and product_sizes tables
//App\Product.php
public function sizes()
{
return $this->belongsToMany('App\ProductSize', 'available_product_sizes', 'product_id', 'product_size_id');
}
//App\ProductSize.php
public function products()
{
return $this->belongsToMany('App\Product', 'available_product_sizes', 'product_size_id', 'product_id');
}
In order to get available product sizes you can use :
$sizes = App\Product::find(1)->sizes()->orderBy('size_name')->get();
Controller fix
public function single_product($product_slug) {
$single_product = Product::with('sizes')->where('product_slug',$product_slug)->first();
return view('front_end/single_product',compact('single_product'));
}
View Fix
//...
#foreach($single_product->sizes as $size)
<tr>
<td>
<b>{{$size->sizes_name}}</b>
</td>
<td>{{$size->Body_length}}</td>
<td>{{$size->Body_width}}</td>
<td>{{$size->Sleeve_length}}</td>
</tr>
#endforeach
//...
Answer to the question without using eloquent
use Illuminate\Support\Facades\DB; //include this
$products = DB::table('products as p')
->join('available_product_sizes as aps','aps.product_id','p.id')
->join('product_sizes ps','ps.id','aps.product_size_id')
->where('product_slug',$product_slug)->get();
But it is highly recommended to use eloquent relationships.
I am trying to retrieve database rows with their relationships. However, the local key is an array. Let me explain using an example.
Lets say I have a table of countries and a table of pages. Each country can have many pages. Each page can belong to multiple countries. I do not have the flexibility to change this schema.
pages
+-------------+-----------+
| id | name | countries |
+-------------+-----------+
| 1 | Page 1 | 1 |
+-------------+-----------+
| 2 | Page 2 | 1,2,3 |
+-------------+-----------+
| 3 | Page 3 | 4,5,6 |
+-------------+-----------+
countries
+----+----------------+
| id | name |
+----+----------------+
| 1 | United States |
+----+----------------+
| 2 | United Kingdom |
+----+----------------+
| 3 | Germany |
+----+----------------+
| 4 | France |
+----+----------------+
| 5 | Hong Kong |
+----+----------------+
| 6 | Thailand |
+----+----------------+
| 7 | Belgium |
+----+----------------+
| 8 | Singapore |
+----+----------------+
My model and controller look something like:
country
public function pages()
{
return $this->hasMany(Page::class, 'id', 'countries');
}
MemberController.php
$countries = Country::with('pages')->get();
This is returning all countries, but only Page 1 contains any relationships.
Is there a way to retrieve relationships using a whereIn approach so all three countries will return appropriate pages?
Thanks in advance
Since Page can belong to many Countries, you need to create a pivot table called country_page and remove the countries column.
Then define two belongsToMany() relationships in both models:
public function pages()
{
return $this->belongsToMany(Page::class);
}
If you're not following Laravel naming conventions listed in my repo and you gave the pivot name a custom name, define it too:
public function pages()
{
return $this->belongsToMany(Page::class, 'custom_pivot_table');
}
Something like this ?
$datas = Pages::where( ##your conditions### )->get()->inArray();
$countries = Countries::pluck('name','id'); // return array of id=>name
foreach($datas as $key=>$data) {
$c = [];
foreach(explode(',',$data['countries']) as $country_id) {
$c[]=$countries[$country_id];
//or
$c[]= ['id'=>$country_id,'name'=>$countries[$country_id]];
}
$datas[$key]['countries']= $c;
}
I have this structure.
class Product extends Model{
public function office()
{
return $this->belongsTo(Office::class,'office_id');
}
}
I want to list products order by office.name.
this is the query
$res = \App\Product::with(['office' => function($q){
$q->orderBy('offices.name','asc');
}])->get();
this is the output loop
foreach($res as $key => $val){
print "<br />user: ".$val->id.", office: ".$val->office->id;
}
this is the Product data:
+----+--------+
| id | name |
+----+--------+
| 1 | Life |
| 2 | Cars |
| 3 | Health |
| 4 | House |
+----+--------+
this is the data in Office
+----+----------------+
| id | name |
+----+----------------+
| 1 | First office |
| 2 | working office |
+----+----------------+
The order by is not affecting the result.
same result, the order by like not existed.
Thanks
In your code you are simply "ordering" the offices by name, which means if each product had many offices, it would sort the offices alphabetically.
To sort (OrderBY()) a collection, the column has to be an attribute of the collection object. One solution could be to Join your models. SOmething like this might help you.
$res = Product::with('office')
->join('offices', 'products.office_id', '=', 'offices.id')
->select('products.*', 'offices.name')
->orderBy('office.name')
->get();