symfony cannt join related tables in manytomany relationship - mysql

I cannot join tables(Products and Category) in ManyToMany relationship.
My Entities
I get this error message when I try to join them
[Syntax Error] line 0, col 511: Error: Expected Literal, got 'JOIN'
My Repository
public function GetProductsList($productid){
$fields = array['product.product','category.category']
$query = $this->getEntityManager()->createQueryBuilder()
->select($fields)
->from('TestMyBundle:product','product')
->innerJoin('TestMyBundle:category','category')
->where('product.productid=:productid')
->setParameter('productid',$productid)
->getQuery()
->getResult();
return $query;
}

Your join looks wrong and I don't see why you need an hardcoded array there. May as well just put the entity aliases directly in the select. I would write that as:
public function GetProductsList($productid){
$result = $this->getEntityManager()->createQueryBuilder()
->select('product', 'category')
->from('TestMyBundle:product','product')
->join('product.categories','category') // making an assumption your product entity has getCategories()
->where('product.productid=:productid')
->setParameter('productid',$productid)
->getQuery()
->getResult();
return $result;
}
Should work then.
Note that when you get problems like this it's useful to do something like ->getSQL() instead of getQuery() and var_dump the SQL to see what the querybuilder is producing, makes it easier to debug.

Related

Add result of subquery to Eloquent query in Laravel 9

In Laravel 9 I am trying to add the result of a subquery to a query(for lack of better wording) and I am stuck. More concretely, I am trying to load all products and at the same time add information about whether the current user has bought that product.
Why do I want to do this?
I am currently loading all products, then loading all bought products, then comparing the 2 to determine if the user has bought a product, but that means extra queries which I would like to avoid. Pretend for the sake of this question that pagination doesn't exist(because when paginating the impact of those multiple queries is far diminished).
There is a many to many relationship between the 2 tables users and products, so these relationships are defined on the models:
public function products()
{
return $this->belongsToMany(Product::class);
}
and
public function users()
{
return $this->belongsToMany(User::class);
}
What I have tried so far:
I created a model for the join table and tried to use selectRaw to add the extra 'column' I want. This throws a SQL syntax error and I couldn't fix it.
$products = Product::query()
->select('id', 'name')
->selectRaw("ProductUser::where('user_id',$user->id)->where('product_id','products.id')->exists() as is_bought_by_auth_user")
->get();
I tried to use addSelect but that also didn't work.
$products = Product::query()
->select('id', 'name')
->addSelect(['is_bought_by_auth_user' => ProductUser::select('product_id')->where('user_id',$user?->id)->where('product_id','product.id')->first()])
->get();
I don't even need a select, I actually just need ProductUser::where('user_id',$user?->id)->where('product_id','product.id')->exists() but I don't know a method like addSelect for that.
The ProductUser table is defined fine btw, tried ProductUser::where('user_id',$user?->id)->where('product_id','product.id')->exists() with hardcoded product id and that worked as expected.
I tried to create a method on the product model hasBeenBoughtByAuthUser in which I wanted to check if Auth::user() bought the product but Auth wasn't recognized for some reason(and I thought it's not really nice to use Auth in the model anyway so didn't dig super deep with this approach).
$products = Product::query()
->select('id', 'name')
->addSelect(\DB::raw("(EXISTS (SELECT * FROM product_user WHERE product_users.product_id = product.id AND product_users.user_id = " . $user->id . ")) as is_bought_by_auth_user"))
->simplePaginate(40);
For all attempts $user=$request->user().
I don't know if I am missing something easy here but any hints in the right direction would be appreciated(would prefer not to use https://laravel.com/docs/9.x/eloquent-resources but if there is no other option I will try that as well).
Thanks for reading!
This should do,
$id = auth()->user()->id;
$products = Product::select(
'id',
'name',
DB::raw(
'(CASE WHEN EXISTS (
SELECT 1
FROM product_users
WHERE product_users.product_id = products.id
AND product_users.user_id = '.$id.'
) THEN "yes" ELSE "no" END) AS purchased'
)
);
return $products->paginate(10);
the collection will have purchased data which either have yes or no value
EDIT
If you want eloquent way you can try using withExists or withCount
i.e.
withExists the purchased field will have boolean value
$products = Product::select('id', 'name')->withExists(['users as purchased' => function($query) {
$query->where('user_id', auth()->user()->id);
}]);
withCount the purchased field will have count of found relationship rows
$products = Product::select('id', 'name')->withCount(['users as purchased' => function($query) {
$query->where('user_id', auth()->user()->id);
}]);

Laravel Select Query Accessing Returned Data

I've been working with Laravel for a short time, and am confused about accessing data retrieved from queries. I'm trying to save data to variable but am getting the following:
Trying to get property of non-object
Queries tried:
$data = DB::table('table_1')->select('user_id', 'email')->where('email', '=', Input::get('email_address'))->get();
// also tried
$data = DB::table('table_1')->where('email', '=', Input::get('email_address'))->pluck('user_id');
// accessing data
$userID = $data->user_id;
Both return the same.
To elaborate a little bit, ->get() will return a Collection. You might iterate over it as an array, but you can profit from methods that this class offers. pluck is one of these.
That's why $userID = $data->user_id; wouldn't work.
first() did the trick, rather than get().
$data = DB::table('table_1')->select('user_id', 'email')->where('email', '=', Input::get('email_address'))->first();

What is wrong with this Code Igniter mySQL query?

I have two tables for storing information about a user. One is for authentication, the other is information the user will enter themselves. I am writing a model that will be used when the user interacts with this information. The following method is to return data for display and modification.
I need a query that will return 'email' and 'username' from $accounts_table and * from $profiles_table. I can't seem to get my head around the JOIN syntax though. I understand how joins work, but my queries throw sentax errors.
function get_userdata($id){
$data = array();
$this->db->get_where($this->profiles_table, array('user_id' => $id));
$this->db->join($this->accounts_table.'.email', $this->accounts_table.'.id = '.$this->profiles_table.'.user_id');
$data= $this->db->get();
return $data;
}
I see a couple of issues:
You should be using $this->db->where(), instead of $this->db->get_where(). get_where() executes the query immediately.
$this->db->get_where('user_id', $id);
Also the first argument of $this->db->join() should only be the table name, excluding the field.
$this->db->join($this->accounts_table, $this->accounts_table.'.id = '.$this->profiles_table.'.user_id');
And you're returning $data which is just an empty array(). You would need to pass the query results to $data like this:
$data = $record->result_array();
get_where executes the query. So, your join is its own query, which doesn't work.
You need to break get_where into where and from.
Also, in MySQL, you JOIN a table, not a field. If you want that field, add it to the SELECT.
$this->db->select($this->profiles_table.'.*');
$this->db->select($this->accounts_table.'.email,'.$this->accounts_table.'.username');
$this->db->from($this->profiles_table);
$this->db->where('user_id', $id);
$this->db->join($this->accounts_table, $this->accounts_table.'.id = '.$this->profiles_table.'.user_id');
$data = $this->db->get();
NOTE: $this->db->get() returns a query object, you need to use result or row to get the data.
I think you've a mistake:
$this->db->join($this->accounts_table.'.email', $this->accounts_table.'.id = '.$this->profiles_table.'.user_id');
First parameter should a table NOT a field: $this->accounts_table.'.email' is wrong IMHO. Or only a typo :)

"No result was found for query although at least one row was expected." Query should display records though in Symfony

I'm trying to retrieve content using two items in the URL. Here is the php/symfony code that should do it:
$em = $this->getDoctrine()->getEntityManager();
$repository = $this->getDoctrine()
->getRepository('ShoutMainBundle:Content');
$query = $repository->createQueryBuilder('p')
->where('p.slug > :slug')
->andWhere('p.subtocontentid > :parent')
->setParameters(array(
'slug' => $slug,
'parent' => $page
))
->getQuery();
$content = $query->getSingleResult();
However, when this code is executed it returns the following error:
No result was found for query although at least one row was expected.
I have done some tests, and the data held in the $slug and $page variables hold the correct information. I have also tested the MySQL query and the query brings up the desired result, which confuses me further.
Have I missed something?
As it was answered here
You are getting this error because you are using the
getSingleResult() method. it generates an Exception if it can't find
even a single result. you can use the getOneOrNullResult() instead
to get a NULL if there isn't any result from the query.
Query#getSingleResult(): Retrieves a single object. If the result
contains more than one object, an NonUniqueResultException is thrown.
If the result contains no objects, an NoResultException is thrown. The
pure/mixed distinction does not apply.
No result was found for query although at least one row was expected.
Another reason could be:
You did this
$query = $this->getEntityManager()
->createQuery('
SELECT u FROM MyBundle:User u
WHERE u.email = :email')
->setParameter('email', $email);
return $query->getSingleResult();
Instead of this
$query = $this->getEntityManager()
->createQuery('
SELECT u FROM MyBundle:User u
WHERE u.email = :email')
->setParameter('email', $email);
$query->setMaxResults(1);
return $query->getResult();
Don't you want to use "=" instead of ">" ?
If you've got this message because used
$content = $query->getSingleResult();
you can just replace it with the row below
$content = $query->getOneOrNullResult(AbstractQuery::HYDRATE_SINGLE_SCALAR) ?? 0;

Doctrine LIMIT Syntax Error?

'[Syntax Error] line 0, col 71: Error: Expected end of string, got 'LIMIT''
Here's my code:
public function getLatestChapters()
{
return $this->_em->createQuery('SELECT c, m FROM models\Chapter c JOIN c.Manga m ORDER BY c.CreateDate LIMIT 10')->getResult();
}
What could posibly the problem for this? How can I use LIMIT in Doctrine?
I am using Doctrine 2
Seems like there is no LIMIT/OFFSET in DQL anymore.
$qb = $em->createQueryBuilder();
//.. build your query
$q = $qb->getQuery();
$q->setFirstResult($offset);
$q->setMaxResults($limit);
$result = $q->getResult();
I would Like to Contribute to this post and want to tell people that If you want to use DBAL with limit in your Unit Tests you can use following:
$client = static::createClient()
$em = $client->getContainer()->get('doctrine')->getManager();
$query = $em->createQuery('WRITE YOUR QUERY HERE');
$query->setFirstResult(0);
$query->setMaxResults(1);
$data = $query->getResult();
Same code can be used in controller also with some modifications :)