Get hasMany relationship with Eloquent Laravel - php

I have two tables with this schmea:
mysql> show columns from table_1;
+-------------+------------------+------+-----+---------------------+-----------
| Field | Type | Null | Key | Default | Extra
+-------------+------------------+------+-----+---------------------+-----------
| id | int(10) unsigned | NO | PRI | NULL | auto_incre
| id_world | int(11) | NO | | NULL |
| key | varchar(255) | NO | | NULL |
| name | varchar(255) | NO | | NULL |
| description | varchar(255) | NO | | NULL |
| level | int(11) | NO | | 0 |
| created_at | timestamp | NO | | 0000-00-00 00:00:00 |
| updated_at | timestamp | NO | | 0000-00-00 00:00:00 |
+-------------+------------------+------+-----+---------------------+-----------
8 rows in set (0.00 sec)
and
mysql> show columns from table_2;
+--------------+------------------+------+-----+---------------------+----------
------+
| Field | Type | Null | Key | Default | Extra
|
+--------------+------------------+------+-----+---------------------+----------
| id | int(10) unsigned | NO | PRI | NULL | auto_incr
| key | varchar(255) | NO | | NULL |
| level | int(11) | NO | | NULL |
| name | varchar(255) | NO | | NULL |
| description | varchar(255) | NO | | NULL |
| price | int(11) | NO | | NULL |
| amount | int(11) | NO | | NULL |
| created_at | timestamp | NO | | 0000-00-00 00:00:00 |
| updated_at | timestamp | NO | | 0000-00-00 00:00:00 |
+--------------+------------------+------+-----+---------------------+----------
30 rows in set (0.00 sec)
I want to get all fields "from table_2 where table_2.key = table_1.key AND table_2.level = 10" is this the right way with the hasMany option in my model?
my normal query looks like this:
SELECT A.key AS p_key,
A.name AS p_key,
A.description AS p_desc,
A.level AS p_level,
B.key AS r_key,
B.level AS r_level,
B.name AS r_name,
B.description AS r_desc
FROM
table_1 AS A,
table_2 AS B
WHERE
B.key = A.key AND
B.level = '1'

To build hasMany relationship using those tables, you need to create two models first, for example:
class TableOne extends Eloquent {
protected $table = 'table_1';
public function tableTwoItems()
{
return $this->hasMany('TableTwo', 'table_2.key', 'table_1.key')
->where('table_2.level', 1);
}
}
class TableTwo extends Eloquent {
protected $table = 'table_2';
}
Once you created these models in your app/models directory then you may use something like this:
$result = TableOne::with('tableTwoItems')->get();
To select the items/fields, you may use something like this:
$result = TableOne::with(array('tableTwoItems' => function($query){
$query->select('table_2.key as k2', 'table_2.name as name2', 'more...');
}))->select('table_1.key as k1', 'table_1.name as name1', 'more...')->get();
You may access them like:
$result->first()->tableTwoItems->first();
Or you may loop $result and also you may loop the related items using nested loop. For example:
foreach($result as $tableOneItem)
echo $tableOneItem->name;
foreach($tableOneItem->tableTwoItems as $tabletwoItem)
echo $tabletwoItem->name;
endforeach;
endforeach;
Try to use different field names in both table's key and make them unique as well. Read the Eloquent Relation documentation for more.

Related

What is the best way to update a one table from another in SQL?

I have 2 tables the first one is the product-page visited
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| idproduct | varchar(128) | YES | | NULL | |
| logdate | date | YES | | NULL | |
| idmagasin | int(20) | YES | | NULL | |
| idenseigne | int(20) | YES | | NULL | |
| commanded | int(2) | YES | | 0 | |
+------------+--------------+------+-----+---------+----------------+
And the second one is the product commanded
+-------------+--------------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+-------------------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| idproduct | varchar(255) | NO | | NULL | |
| idenseigne | int(11) | NO | | NULL | |
| idmagasin | int(11) | NO | | NULL | |
| ingredients | tinytext | YES | | NULL | |
| date | timestamp | NO | | CURRENT_TIMESTAMP | |
+-------------+--------------+------+-----+-------------------+----------------+
How can i update the column commanded in product_visited , if product_visited.idproduct = product_commanded.idproduct and product_visited.logdate = product_commanded.date
i'm confused to use inner join or exists
I want to update product_visited.commanded = 1 when the value of logdate and idproduct exists in product_commanded, it will mean the product visited is commanded too
I believe this is what you are looking for:
Update product_visited pv
set commanded = 1
Where exists (Select 1
from product_commanded pc
where pv.idproduct = pc.idproduct and pv.logdate = pc.date
);
Ok, I've made guesses with the join fields but you're after something like this;
UPDATE pv
SET pv.Commanded = 1
FROM Product_Visited pv
JOIN Product_Commanded pc
ON pv.logdate = pc.date
AND pv.idproduct = pc.id
The inner join means that you're only going to update records in Product_Visited where there are matching rows in Product_Commanded based on the join predicates you give it.
Note: this is a SQL Server answer. May or may not work in MySQL
Sounds like you want to update commanded whenever a record exists for same product in commanded table?
in any database:
Update product_visited set commanded = 1
Where exists(Select * from product_commanded
where product_id = product_visited.Product_id)

Eloquent IF clause - always returns true

I am using Entrust's default table structure:
permissions table:
+--------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | UNI | NULL | |
| display_name | varchar(255) | YES | | NULL | |
| description | varchar(255) | YES | | NULL | |
| created_at | timestamp | NO | | NULL | |
| updated_at | timestamp | NO | | NULL | |
+--------------+------------------+------+-----+---------+----------------+
permission_role table:
+---------------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+------------------+------+-----+---------+-------+
| permission_id | int(10) unsigned | NO | PRI | NULL | |
| role_id | int(10) unsigned | NO | PRI | NULL | |
+---------------+------------------+------+-----+---------+-------+
roles table:
+--------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | UNI | NULL | |
| display_name | varchar(255) | YES | | NULL | |
| description | varchar(255) | YES | | NULL | |
| created_at | timestamp | NO | | NULL | |
| updated_at | timestamp | NO | | NULL | |
+--------------+------------------+------+-----+---------+----------------+
Now, given a role_id I'd like to get select the following from this database:
permissions.id
permissions.display_name
whether the permission_role table contains an entry with the permission_id and the given role_id
The last one turned out to be a bit tricky in Eloquent.
This SQL query accomplishes exactly what I need (ID is obviously replaced by a valid role ID):
SELECT p.id, p.display_name, IF(pr.role_id = ID, 1, 0) AS has_role
FROM permissions p
LEFT OUTER JOIN permission_role pr ON p.id = pr.permission_id;
Example output:
+----+--------------+----------+
| id | display_name | has_role |
+----+--------------+----------+
| 1 | Edit users | 1 |
| 2 | View users | 0 |
| 3 | Delete users | 0 |
+----+--------------+----------+
Can anyone help me out here, on how to do this using Eloquent?
I've tried this, but it always returns 1 (true) in the third column, unlike the SQL query (as seen above).
$result = DB::table('permissions')
->leftJoin('permission_role', 'permission_role.permission_id', '=', 'permission_role.role_id')
->select(DB::raw('permissions.id, permissions.display_name, IF(permission_role.role_id = ID, 1, 0) AS has_role'))
->get();
Ideally, I'd like to do this without using DB::raw, although it is completely fine if that is what it takes.
Thanks in advance for any help!
Structurally, the Query Builder query you've shown looks fine.
What does not look fine is the left join. Shouldn't this:
->leftJoin('permission_role', 'permission_role.permission_id', '=', 'permission_role.role_id')
be this:
->leftJoin('permission_role', 'permission_role.permission_id', '=', 'permissions.id')
?

Doing a proper Join with SQL

Suppose I have two tables, one with list of spells and another with a grimory, the list of spells that a user has selected for learn or already learned.
mysql> SHOW COLUMNS FROM Grimory;
+--------------+------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| personage_id | int(11) | YES | MUL | NULL | |
| spell_id | int(11) | YES | MUL | NULL | |
| isLearned | tinyint(1) | NO | | NULL | |
| isSelected | tinyint(1) | NO | | NULL | |
+--------------+------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)
mysql> SHOW COLUMNS FROM Spell;
+-----------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | | NULL | |
| description | longtext | NO | | NULL | |
| chatDescription | longtext | NO | | NULL | |
| level | int(11) | NO | | NULL | |
| isActive | tinyint(1) | NO | | NULL | |
| category_id | int(11) | YES | MUL | NULL | |
| createdAt | datetime | YES | | NULL | |
+-----------------+--------------+------+-----+---------+----------------+
8 rows in set (0.00 sec)
The problem.
I want to display a list with ALL spells by category_id, BUT for every row I want to show if that spell is learned or selected by current user (personage_id).
Can you help me to write a proper query?
How this works:
With php I generate: List of spells | checkbox isSelected | checkBox isStudied
When I click on isSelected checkbox, a record in grimory will be added with current user and spell.
Updated
SELECT a.*, IFNULL(b.isLearned,0) as isLearned,
IFNULL(b.isSelected,0) as isSelected
FROM Spell a
LEFT JOIN Grimory b(ON b.spell_id =a.id
AND b.personage_id =:current_user_id)
WHERE a.category_id = :current_category_id
SELECT * FROM Spell
INNER JOIN Grimory
ON Spell.id = Grimory.spell_id
WHERE (Grimory.isLearned = 1 OR Grimory.isSelected = 1)
AND Spell.category_id = 'YOUR CAT ID IS HERE'

How can i set association between comment model and Users.User model?

It's CakePHP-2.0 and CakeDC-Users plugin
mysql> describe comments;
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| post_id | int(11) | NO | MUL | NULL | |
| user_id | int(11) | NO | | NULL | |
| body | varchar(500) | NO | | NULL | |
| mark | tinyint(4) | NO | | 1 | |
| created | datetime | YES | | NULL | |
| modified | datetime | YES | | NULL | |
+----------+--------------+------+-----+---------+----------------+
7 rows in set (0.00 sec)
I need the username not the user_id. How can i set the association between Users.User model and Comment model and with Post model.
So far i have this in Comment model public $belongsTo = array('Post','Users.User');
Can anyone please explain with example about this association?
the field user_id is a foreign key in that table.
Cake will automatically fetch records related to that id, including username and other fields depending on your recursive level.

Force Specific Record to Top When Performing GROUP BY

I have the following MySQL query and tables from which I am querying:
SELECT
`Song`.`id`,
`Song`.`file_name`,
`User`.`first_name`,
`Vote`.`value`,
Sum(`Vote`.`value`) AS score
FROM `songs` AS `Song`
LEFT JOIN votes AS `Vote` ON (`Song`.`id`=`Vote`.`song_id`)
LEFT JOIN `users` AS `User` ON (`Song`.`user_id` = `User`.`id`)
GROUP BY `Vote`.`song_id`
LIMIT 20;
mysql> describe songs;
+-----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| file_name | varchar(255) | NO | | NULL | |
| user_id | int(11) | NO | | NULL | |
| created | datetime | NO | | NULL | |
| modified | datetime | NO | | NULL | |
+-----------+--------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)
mysql> describe users;
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| username | varchar(255) | NO | | NULL | |
| password | varchar(255) | NO | | NULL | |
| first_name | varchar(255) | NO | | NULL | |
| last_name | varchar(255) | NO | | NULL | |
| is_admin | tinyint(1) | NO | | 0 | |
| created | datetime | NO | | NULL | |
| modified | datetime | NO | | NULL | |
+------------+--------------+------+-----+---------+----------------+
mysql> describe votes;
+----------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+----------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| value | int(11) | NO | | NULL | |
| song_id | int(11) | NO | | NULL | |
| user_id | int(11) | NO | | NULL | |
| created | datetime | NO | | NULL | |
| modified | datetime | NO | | NULL | |
+----------+----------+------+-----+---------+----------------+
This query functions just like I want except for one thing. The value returned in the field Vote.value is not from a row that is associated with the user who is logged into the application. I need the score value to be a sum of all the values no matter which user it is associated with, but the Vote.value field should belong to the logged in user (each user only gets one vote record per song).
My first thought is to somehow sort the table so that when the group by happens the vote record for the logged in user is at the top but I have no idea how to do a sort that forces an arbitrary value to the top. Any ideas would be very helpful.
and a third join
LEFT JOIN votes AS `VotePerUser` ON (`Song`.`id`=`Vote`.`song_id`
AND `Song`.`user_id`=`votes`.`user_id`)
and replace the Vote.value with VotePerUser.Value

Categories