Laravel - Get sum from different table and calculate - laravel

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.

Related

How Products is order by relation in Laravel?

How can I sort the products in table1 according to their connection with table2 i.e. sort the products in table1 by example_relation in table2?
Table1
| id | product |
|----|---------|
| 1 | pro1 |
| 2 | pro2 |
| 3 | pro3 |
| 4 | pro4 |
| 5 | pro5 |
Table2
| id | example_relation | product_id |
|----|------------------|------------|
| 1 | 700 | 1 |
| 2 | 800 | 2 |
| 3 | 900 | 3 |
| 4 | 850 | 2 |
| 5 | 600 | 4 |
| 6 | 125 | 5 |
Table1 model page:
public $belongsTo = [
'pro_relation' => [
'models\Model',
'key' => 'id',
'otherKey' => 'product_id',
],
Sorting section that needs to be arranged correctly:
$query->whereHas('pro_relation', function($q) use ($postFrom,$postTo){
$q->select('example_relation END AS expose');
})->orderBy("expose", DESC);
Okay, when you want to order the result of one table from another table then you can use orderBy() inside a closure of the relationship to another table.
So from your query, you can add orderBy() like so.
$query->whereHas('pro_relation', function($q) use ($postFrom,$postTo){
$q->select('example_relation END AS expose')
->orderBy('example_relation');
});
This is work
$query->join('table2', 'table1.id', '=', 'table2.yacht_id')
->orderBy(example_relation DESC);

Laravel - Get Data from Table where clause in other table

I have this following 2 tables:
Table: Products
+----+---------+-------------+
| id | fn_id | created_at |
+----+---------+-------------+
| 1 | 4 | SOME TIME |
| 2 | 5 | SOME TIME |
| 3 | 6 | SOME TIME |
| 4 | 10 | SOME TIME |
| 5 | 10 | SOME TIME |
+----+---------+-------------+
Table Fn
+----+---------+-------------+
| id | fn_id | created_at |
+----+---------+-------------+
| 1 | 10 | SOME TIME |
| 2 | 11 | SOME TIME |
| 3 | 12 | SOME TIME |
| 4 | 14 | SOME TIME |
+----+---------+-------------+
And a User Input which is giving me a timestamp ($user_timestamp).
Now I need to get all produtcs, where
products.fn_id is 10
fn.fn_id is 10
fn.created == $user_timestamp
The products model has this relation:
public function fn() {
return $this->hasMany('App\FN', 'fn_id', 'fn_id');
}
Now I've tried multiple things like a where query where I want to check if the fn_id on both are "10" and the created_at value of the fn table is equal to $user_timestamp.
However, I wasn't able to do it.
$products = Products::with('fn')->where('fn.fn_id', function ($query) use ($user_timestamp) {
$query->where([['fn_id', 10],['created_at', $user_timestamp]]);
})->get();
You would have to use whereHas to constrain Products based on fn.
$products = Products::with('fn')->whereHas('fn', function($q) use($user_timestamp){
$q->where('fn_id', 10)->where('created_at', $user_timestamp);
})->get();
try this
$id_to_search=10;
$products = Products::with('fn')->where('fbn_id',$id_to_search)->whereHas('fn', function($q) use($user_timestamp,$id_to_search){
$q->where('fn_id', $id_to_search)->where('created_at', $user_timestamp);
})->get();

Laravel Eloquent How to Combine Many to Many and One to Many relationships with 3 table

I have a database like this.
+----------------+
| Tables_in_test |
+----------------+
| a_b |
| a_c |
| as |
| bs |
| cs |
+----------------+
bs and cs tables have many to many relationship with as table. So a_b table and a_c table are pivot tables.
This is as table
+----+------+
| id | name |
+----+------+
| 1 | A1 |
| 2 | A2 |
+----+------+
This is bs table
+----+------+
| id | name |
+----+------+
| 1 | B1 |
+----+------+
And this is cs table
+----+------+------+
| id | b_id | name |
+----+------+------+
| 1 | 1 | C1 |
| 2 | 1 | C2 |
+----+------+------+
this is a_b pivot table
+------+------+
| a_id | b_id |
+------+------+
| 1 | 1 |
+------+------+
And this is a_c pivot table.
+------+------+
| a_id | c_id |
+------+------+
| 1 | 1 |
| 2 | 2 |
+------+------+
And this is my A model for the as table.
class A extends Model
{
protected $table = "as";
public function b(){
return $this->belongsToMany("App\B");
}
public function c(){
return $this->belongsToMany("App\C");
}
}
And this is B model for bs table
class B extends Model
{
protected $table = "bs";
public function c(){
return $this->hasMany("App\C");
}
}
I just want to query C table values as related to A table.
I tried this query
A::where("id",1)->with("b.c")->get();
But this result also gives me C2 value which is related to A2 in "as" table. I want to get only C1 value which is related only A1 value in "as" table.
How can I do this ? Thank you for your help
In your example data A1 relates to B1 which in turn relates to C2. And you are in fact nesting the b.c eager load, so you are loading Bs and Cs related to those Bs.
Have you tried A::where("id",1)->with(["b", "c"])->get();
?

SAS/STAT 12.1: KEYLABEL in PROC TABULATE: need row total and column total lines for "all" to display different labels

I am working in SAS/STAT 12.1 and I have only one issue with my code below, I need to show "Total" for the bottom row (displaying columns sums and percentages), instead of "Both Genders." And yes, the top right-hand column header (displaying row totals and percentages) still needs to be "Both Genders."
I hope there is a simple way to do this using keylabel, but haven't figured it out so far.
proc tabulate data=dmhrind format=8.1;
format gender $gendfmt. ethnic $ethnic.;
class ethnic gender;
table (ethnic all)*f=4. , (gender all)*(n*f=4. colpctn*f=5.1 rowpctn*f=5.1) ;
title 'Ethnic Distribution by Gender';
label ethnic='Race/Ethnicity';
keylabel N='N' colpctn='%' all='Both Genders' reppctn='%' rowpctn = 'Total';
run;
Thanks in advance for any assistance provided.
The only way to do this that I can see is to make a dummy column that simulates All. Using sashelp.class:
data class;
set sashelp.class;
allage = 'All Ages';
run;
proc tabulate data=class format=8.1;
class sex age allage;
table (age allage=' ')*f=4. , (sex all)*(n*f=4. colpctn*f=5.1 rowpctn*f=5.1) ;
title 'age Distribution by sex';
label age='Age';
label allage='All Ages';
keylabel N='N' colpctn='%' all='Both Sexes' reppctn='%' rowpctn = 'Total';
run;
It needs to have the text you want as the label as its actual value, and you need to replace all in the tabulate with that variable (and add it to the class statement), and add =' ' to override the extra label subrow.
For this, you need to do the titling within the table statement. The following example is similar to yours, using sashelp.class (as in #Joe's example) where age is used as your ethnicity variable:-
** This option helps improve proc tabulate output on some systems;
options formchar="|----||---|-/\<>*";
** The key is adding the column titles directly in the table stmt;
proc tabulate data=sashelp.class format=8.1;
class sex age;
table (age all='Total')*f=4. , (sex='' all='Both Sexes')*(n='N'*f=4. colpctn='Col %'*f=5.1 rowpctn='Row %'*f=5.1) ;
run;
The output should look like this:-
---------------------------------------------------------------------------
| | F | M | Both Sexes |
| |----------------|----------------|-----------------
| | N |Col %|Row %| N |Col %|Row %| N |Col %|Row %|
|----------------------|----|-----|-----|----|-----|-----|----|-----|------
|Age | | | | | | | | | |
|----------------------- | | | | | | | | |
|11 | 1| 11.1| 50.0| 1| 10.0| 50.0| 2| 10.5|100.0|
|----------------------|----|-----|-----|----|-----|-----|----|-----|------
|12 | 2| 22.2| 40.0| 3| 30.0| 60.0| 5| 26.3|100.0|
|----------------------|----|-----|-----|----|-----|-----|----|-----|------
|13 | 2| 22.2| 66.7| 1| 10.0| 33.3| 3| 15.8|100.0|
|----------------------|----|-----|-----|----|-----|-----|----|-----|------
|14 | 2| 22.2| 50.0| 2| 20.0| 50.0| 4| 21.1|100.0|
|----------------------|----|-----|-----|----|-----|-----|----|-----|------
|15 | 2| 22.2| 50.0| 2| 20.0| 50.0| 4| 21.1|100.0|
|----------------------|----|-----|-----|----|-----|-----|----|-----|------
|16 | .| .| .| 1| 10.0|100.0| 1| 5.3|100.0|
|----------------------|----|-----|-----|----|-----|-----|----|-----|------
|Total | 9|100.0| 47.4| 10|100.0| 52.6| 19|100.0|100.0|
--------------------------------------------------------------------------|

How are product attributes and attribute options stored in Magento database?

I am trying to figure out how the linkage between attribute and attribute options, and product and attributes are made in Magento. Is there any reference to how this is working? or anyone give me a hint on this.
Thanks,
Balan
As Alan Storm says: "you do not have to know about how your db works. You have to learn how the models work ". (This is not an exact quote. I gave you the meaning).
But I created own scheme to understand the DB structure. So this screen shows how it works:
Hope, it helps.
Also I recommend you to look through these links:
http://www.magentocommerce.com/wiki/2_-_magento_concepts_and_architecture/magento_database_diagram
http://alanstorm.com/magento_advanced_orm_entity_attribute_value_part_1
1) The attributes are stored in eav_attribute. There you get the attribute_id.
2) The options are stored in eav_attribute_option_value. There yout get the option_id.
3) The options are assigned to the product in catalog_product_entity_varchar. There you need the entity_id of the product, the attribute_id from 1) and the value which are the comma separated option_ids from 2)
I've found these queries to be very helpful for hunting down things like - where does it say the product color is black?, for example.
-- show_product_attr.sql
select
p.entity_id,
p.entity_type_id,
p.attribute_set_id,
p.type_id,
p.sku,
a.attribute_id,
a.frontend_label as attribute,
av.value
from
catalog_product_entity p
left join catalog_product_entity_{datatype} av on
p.entity_id = av.entity_id
left join eav_attribute a on
av.attribute_id = a.attribute_id
where
-- p.entity_id = 28683
-- p.sku = '0452MR'
p.entity_id = {eid}
;
And for attr_options
-- show_product_attr_options.sql
select
p.entity_id,
-- p.entity_type_id,
-- p.attribute_set_id,
p.type_id,
p.sku,
a.attribute_id,
a.frontend_label as attribute,
-- a.attribute_code,
av.value,
ao.*
from
catalog_product_entity p
left join catalog_product_entity_int av on
p.entity_id = av.entity_id
left join eav_attribute a on
av.attribute_id = a.attribute_id
left join eav_attribute_option_value ao on
av.value = ao.option_id
where
-- p.entity_id = 28683
p.entity_id = {eid}
;
You need to replace {datatype} with text, varchar, int, decimal, etc, for the first query, and {eid} with entity_id for both queries. Which you can do on the command like like this:
$ cat show_product_attr_options.sql | sed -e "s/{eid}/30445/" | mysql -uUSER -pPASS DATABASE -t
+-----------+---------+--------------+--------------+---------------------------+-------+----------+-----------+----------+--------------------+-------------+
| entity_id | type_id | sku | attribute_id | attribute | value | value_id | option_id | store_id | value | colorswatch |
+-----------+---------+--------------+--------------+---------------------------+-------+----------+-----------+----------+--------------------+-------------+
| 30445 | simple | 840001179127 | 96 | Status | 1 | 5972 | 1 | 0 | Male | NULL |
| 30445 | simple | 840001179127 | 102 | Visibility | 1 | 5972 | 1 | 0 | Male | NULL |
| 30445 | simple | 840001179127 | 122 | Tax Class | 2 | 5973 | 2 | 0 | Female | NULL |
| 30445 | simple | 840001179127 | 217 | Size | 257 | 17655 | 257 | 0 | XS | NULL |
| 30445 | simple | 840001179127 | 217 | Size | 257 | 17657 | 257 | 1 | XS | NULL |
| 30445 | simple | 840001179127 | 224 | Color | 609 | 18717 | 609 | 0 | Arctic Ice Heather | NULL |
| 30445 | simple | 840001179127 | 260 | Featured | 0 | NULL | NULL | NULL | NULL | NULL |
| 30445 | simple | 840001179127 | 262 | Clearance Product | 0 | NULL | NULL | NULL | NULL | NULL |
| 30445 | simple | 840001179127 | 263 | Skip from Being Submitted | 0 | NULL | NULL | NULL | NULL | NULL |
| 30445 | simple | 840001179127 | 283 | Discontinued | 0 | NULL | NULL | NULL | NULL | NULL |
+-----------+---------+--------------+--------------+---------------------------+-------+----------+-----------+----------+--------------------+-------------+
A similar set of sql scripts can be created for catalog.
Product Attributes are extra values that you can assign to a product and is stored in the main EAV table, by name, and the data is then stored in a few different tables based on the data type, like varchar, decimal, text Integer, date, etc.
if you had multiple values for your Product Attribute, then that will be stored in the Attribute Options tables, again, different tables based on the data type.
the following link explains the relationships better:
http://www.magentocommerce.com/wiki/2_-_magento_concepts_and_architecture/magento_database_diagram
And deeper developer's detail:
http://www.magentocommerce.com/knowledge-base/entry/magento-for-dev-part-7-advanced-orm-entity-attribute-value
And Attribute sets will be the other thing you come across, like the name suggests, a set of attributes grouped together. http://www.magentocommerce.com/knowledge-base/entry/how-do-i-create-an-attribute-set
HTH
Shaun
SELECT pei.value
FROM `catalog_product_entity_int` pei
JOIN `eav_attribute` ea
ON pei.attribute_id = ea .attribute_id
WHERE pei.entity_id = {your product_id}
AND ea.attribute_code = '{your attribute_code}'
Note that there are a number of different tables like catalog_product_entity_int depending on the type of the attribute, so one of those other ones could be appropriate.
You can get all product properties by using this query:
SELECT CPEV.entity_id, CPE.sku, EA.attribute_id, EA.frontend_label, CPEV.value
FROM catalog_product_entity_varchar AS CPEV
INNER JOIN catalog_product_entity AS CPE ON CPE.entity_id = CPEV.entity_id
INNER JOIN eav_attribute AS EA ON(CPEV.attribute_id = EA.attribute_id AND EA.entity_type_id = 4)
INNER JOIN catalog_eav_attribute AS CEA ON(CEA.attribute_id = EA.attribute_id AND CEA.is_visible_on_front = 1 AND CEA.is_visible_in_grid = 1)

Resources