I would like to recover the user who wrote the post, only I have an error when I try to do it "Attempted to call an undefined method named "getIdPost" of class "App\Entity\User"."
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery( //creation de la requête
'SELECT p , u
FROM App\Entity\User u, App\Entity\Post p
WHERE p.Id_Post_Parent IS NULL
AND p.Id_User = u.idUser
ORDER BY p.Post_Date_Time DESC'
)->setMaxResults(10);
$posts = $query->getResult();
$publicPosts = array();
$comments = array();
for($i = 0; $i<sizeof($posts) ; $i++){
$publicPosts[$i] = $posts[$i]->getArray();
//récupération des commentaires
$em = $this->getDoctrine()->getManager(); //on appelle Doctrine
$query = $em->createQuery( //creation de la requête
'SELECT p , u
FROM App\Entity\User u, App\Entity\Post p
WHERE p.Id_Post_Parent = :idParent
AND p.Id_User = u.idUser'
)->setParameter('idParent', $posts[$i]->getIdPost())
->setMaxResults(10); //On limite à 10 commentaires par posts
$comments[$i] = $query->getResult(); //variable qui récupère la requête
}
If I remove the User entity of the query it works and I have no error ... I do not understand what it's due, why it tells me that there is no method "getIdPost" in user? This is normal since it is a method of "Post" :x
you would like the user who wrote the post it's a bit weird to get it from a query don't you have a $post->getUser() ? I think you should join the table to acheive that
$query = $em->createQuery( //creation de la requête
'SELECT u
FROM App\Entity\User u,
LEFT JOIN App\Entity\Post p on p.Id_User = u.idUser
WHERE p.Id_Post_Parent IS NULL
ORDER BY p.Post_Date_Time DESC'
)->setMaxResults(10);
Related
I have a RSform (3.0.18) in Joommla (3.10.9) on server PHP (7.4.21).
One of the fields is a Dropdown (no multiselect) with a query SQL to get article from catid 15 OR 16. Thhe code below is given by RSForm documentation and adapted to my need.
//<code>
// Prepare the empty array
$items = array();
// Prepare the database connection
$db = JFactory::getDbo();
// Keep this if you'd like a "Please select" option, otherwise comment or remove it
$items[] = "|Sélectionnez...[c]";
// Run the SQL query and store it in $results
$db->setQuery("SELECT id, title FROM #__content WHERE catid = 15 or catid = 16");
$results = $db->loadObjectList();
// Now, we need to convert the results into a readable RSForm! Pro format.
// The Items field will accept values in this format:
// value-to-be-stored|value-to-be-shown
// Eg. m|M-sized T-shirt
foreach ($results as $result) {
$value = $result->id;
$label = $result->title;
$items[] = $value.'|'.$label;
}
// Multiple values are separated by new lines, so we need to do this now
$items = implode("\n", $items);
// Now we need to return the value to the field
return $items;
//</code>
The query works and I get a result like :
Sélectionnez...
Introduction aux médias et à la prise de parole en public
Réussir une prise de parole
Réussir une interview
Médiatraining élus
But I would like it group by catid, which could give something like :
Sélectionnez...
Enterprises formations (not selectable)
Introduction aux médias et à la prise de parole en public
Réussir une prise de parole
Réussir une interview
Administrations formations (not selectable)
Médiatraining élus
Any advice to help writing this ?
Thanks in advance...
I am curious as to how best achieve this.
wpdb query 1:
$results = $wpdb->get_results(
"SELECT *
FROM $table_name
WHERE user_id = '$userid';"
);
I then want to do another wpdb query on a separate table using $results->post_id in the WHERE part of the query such as:
$results2 = $wpdb->get_results(
"SELECT *
FROM $table_name2
WHERE user_id = '$results->post_id' && type = '$type';"
);
I am conscious that $results will be an array so I don't think the above will work directly and some sort of compound "for each" seems cumbersome.
What are my options please?
Update example based on Jarlh's comment
$userid = get_current_user_id();
global $wpdb;
$table_name = $wpdb->prefix . 'postmeta';
$table2_name = $wpdb->prefix . 'posts';
$rewards_results = $wpdb->get_results(
"SELECT *
FROM $table_name
WHERE post_id in ("SELECT user_id
FROM $table2_name
WHERE user_id = '$userid';")"
);
Update 2:
$userid = get_current_user_id();
global $wpdb;
$table_name = $wpdb->prefix . 'postmeta';
$table2_name = $wpdb->prefix . 'posts';
$results = $wpdb->get_results(
"SELECT *
FROM $table_name
WHERE ID in (SELECT user_id
FROM $table2_name
WHERE user_id = '$userid')"
);
//return $results;
foreach ($results as $row) {
echo "<td class='dash-2-td'>" . esc_html($row->logo_id) . "</td>";
echo "<td class='dash-2-td'>" . esc_html($row->belongs_to) . "</td>";
echo "</tr>";
}
This is producing no output.
I need to search $table_name->post_id for rows that match $table2_name->ID where user_id = $userid
Update 3: print_r is just showing array(), seems empty
$userid = get_current_user_id();
global $wpdb;
//$table_name = $wpdb->prefix . 'postmeta';
//$table2_name = $wpdb->prefix . 'posts';
$results = $wpdb->get_results(
"SELECT $wpdb->posts.*
FROM $wpdb->posts, $wpdb->postmeta
WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id
AND $wpdb->posts.post_author = $userid
AND $wpdb->postmeta.plan = 3981
");
return $results;
I ended up using wp_query which I had not even considered as an option.
As a solution, you can use INNER JOIN. Also, I'd suggest you to use $wpdb->prepare for escaping values. Here is an example:
$sql = $wpdb->prepare( "SELECT a.*, b.col1, b.col2 FROM $table1 as a INNER JOIN $table2 as b ON a.user_id = b.user_id WHERE a.user_id = %d AND b.type = %s", $user_id, $type );
$entries = $wpdb->get_results( $sql, ARRAY_A );
Hope it helps.
I do search function In raw SQL like this
//test condition variable
if ($param_type != "") {
if($param_type =='SAS'){
$str .= " AND pos.type IN('SAS1','SAS2') ";
}
else if($param_type =='SME'){
$str .= " AND pos.type IN('SME1','SME2') ";
}
else if($param_type =='PT'){
$str .= " AND pos.type IN('PT','PT0') ";
}else{
$str .= " AND pos.type ='$param_type'";
}
}
//SQL
$query =" SELECT * FROM tbl_user AS u INNER JOIN tbl_position AS pos
ON u.user_id = pos.user_id where u.levels IN ('7','8','9') .$str ;" ;
How I can write SQL like this in laravel ?
You can use raw query.
$query = DB::select(SELECT * FROM tbl_user AS u INNER JOIN tbl_position AS pos
ON u.user_id = pos.user_id where u.levels IN ('7','8','9') .$str ;");
Of course then you need to add at the top in your controller use DB;
Anyway Raw queries may be dangerous and it's better to use query builder.
Simple example:
$query = DB::table('tbl_user')
->join('tbl_position','tbl_user.user_id','=','tbl_position.user_id')
->where('something','=','something')
->get();
Query builder: query builder
Reply to my question for who meet problem like me:
Example like this
$query = DB::table('user');
if ($param_type =='PT')
$query->where('pos.type', '=', 1);
}
$result = $query->get();
i have :
public function findTodasLasCompras($usuario_id)
{
$em = $this->getEntityManager();
$dql = 'SELECT v, o, t
FROM OfertaBundle:Venta v
JOIN v.oferta o
JOIN o.tienda t
WHERE v.usuario = :id
ORDER BY v.fecha DESC';
$consulta = $em->createQuery($dql);
$consulta->setParameter('id', $usuario_id);
$result = $consulta->getResult();
return $consulta->getResult();
}
and when i execute it fails with it's error:
ContextErrorException: Notice: Undefined index: Cupon\OfertaBundle\Entity\Oferta in C:\wamp\www\sympony\vendor\doctrine\orm\lib\Doctrine\ORM\Internal\Hydration\ObjectHydrator.php line 477
in C:\wamp\www\sympony\vendor\doctrine\orm\lib\Doctrine\ORM\Internal\Hydration\ObjectHydrator.php line 477
at ErrorHandler->handle('8', 'Undefined index: Cupon\OfertaBundle\Entity\Oferta',
help! please! Thanks
Try to tranform your 'JOIN' to 'LEFT JOIN'.
If an usario exists well with id 8, maybe he is not linked to oferta or tienda, so the jointure return nothing, but left join keep usario instance.
First of all, replace this:
$result = $consulta->getResult();
return $consulta->getResult();
with this:
$result = $consulta->getResult();
return $result;
Maybe you should reinstall Symphony, it seems something is broken.
I have this working query:
$q = $this->db->query('SELECT u.name FROM users u
JOIN user_group ug ON u.id = ug.user_id
JOIN groups g ON g.id = ug.group_id WHERE ug.group_id = "4" ');
And I want to replace it with aactive record. I come up with something like this but obviously it doesn't work :
$this->db->select('name');
$this->db->from('users');
$this->db->join('user_group', 'user_group.user_id = users.id);
$this->db->join('groups', 'groups.id = user_group.group_id');
$q = $this->db->get();
Thanks
Leron
I think you forget add where clause. And there was single quote missing.
$this->db->select('name');
$this->db->from('users');
$this->db->join('user_group', 'user_group.user_id = users.id');
$this->db->join('groups', 'groups.id = user_group.group_id');
$this->db->where('user_group.group_id', 4);
$q = $this->db->get();