Laravel Querying Views - php

I have a view like this:
CREATE VIEW orders_sales AS
SELECT code, SUM(quantity) * SUM(sale_price) as product_total, shop_id
FROM `orders`
GROUP BY code, product_id
I am trying to query it like this:
$data = DB::table('orders_sales')->get();
I am getting the following error:
SQLSTATE[42000]: Syntax error or access violation: 1055
'pakishops2.orders.shop_id' isn't in GROUP BY (SQL: select * from
orders_sales)
I am able to query it in phpmyadmin like select * from orders_sales but it wont query with Laravel.
enter image description here
EDIT:
I have changed view name to view_saleorders, still no luck

Go to the config/database.php file and check if the option strict is set to true.
Set it to false and you query will work.

Try alternative now,
Create model with that name as laravel standard,
like
class ViewOrders extends Eloquent
Add namespaces required inside model if any.
then create class variable as
protected $table = 'your-view-name';
And now check data by getting like,
ViewOrders::all();
And check if you are getting data.
add strict => false in config/database.php.
If this is set to true then it'll add the ONLY_FULL_GROUP_BY when querying.
Alternative to be more specific with modes,
'modes' => [
'NO_ZERO_DATE',
'ONLY_FULL_GROUP_BY',
],

Sorry to revive an old post, but your view is wrong. You need to match your columns to your GROUP BY clause.
Either change shop_id to product_id, or product_id to shop_id.
-- This is wrong.
CREATE VIEW orders_sales AS
SELECT code, SUM(quantity) * SUM(sale_price) as product_total, <!shop_id!>
FROM `orders`
GROUP BY code, <!product_id!>

Related

Symfony 3 - Doctrine - Difficulties on big query

I'm annoyed because of a big query that goes a little in all directions.
She will use several tables:
User
Package
User Type
PackageDDLExternal (with foreign key User.id and Package.id to which I added a date attribute)
The purpose of this query is to be able to return a list that will contain:
The different existing packages with the number of times they were downloaded, for a certain period, with a given order (ASC or DESC) on the number of downloads, and all this depending on the user types whose ID table has passed as parameter.
So, I've :
Paquet :
Type Utilisateur :
User:
The manyToMany relation between TypeUtilisateur and Paquet:
And the PackageDDLExternal:
So I have already tried to create this query, but there seems to be synthax errors on the one hand (at the level of adding the order) and other things that seem to block...
public function getPackagesDDLBetween($debut, $fin,$typesUser,$ordre)
{
$qb = $this->createQueryBuilder('p');
$queryBuilder = $qb
->select("pa.titre, count(p.package)")
->join("p.package","pa")
->join("p.user","u")
->where("p.date between :debut and :fin")
->andWhere($qb->expr()->in("u.typeUser", $typesUser[0]))
->groupBy("pa.titre")
->orderBy("count(p.package) :ordre")
->setParameter('debut',$debut)
->setParameter('fin',$fin)
->setParameter('ordre', $ordre);
return $queryBuilder->getQuery()->getResult();
}
Using the $order, I get this error:
[Syntax Error] line 0, col 213: Error: Expected known function, got
'count'
But without it, my result is just null
Someone can help me please ?
EDIT: The query is almost good. The problem remains at:
->andWhere($qb->expr()->in("u.typeUser", $typesUser))
My $ tabUser is worth this:
Use an alias:
->select("pa.titre, count(p.package) as total")
Order by alias:
->orderBy("total", $ordre)

QueryException in laravel 5.6

I have converted an sql into laravel query so I came with this below.
DB::table('posts')
->select('posts.*', DB::raw('GROUP_CONCAT(l.name ORDER BY l.id) as location_name'))
->join('locations as l', "posts.location_ids", "=", "l.id")
->whereRaw('FIND_IN_SET(l.id, posts.location_ids) > 0')
->where("posts.status", 'active')
->groupBy('posts.id')
->get();
But it gives me an error.
SQLSTATE[42000]: Syntax error or access violation: 1055 'laraveltest.posts.title' isn't in GROUP BY (SQL: select `posts`.*, GROUP_CONCAT(l.name ORDER BY l.id) as location_name from `posts` inner join `locations` as `l` on `posts`.`location_ids` = `l`.`id` where FIND_IN_SET(l.id, posts.location_ids) > 0 and `posts`.`status` = active group by `posts`.`id`)
When I run this query into any mysql tool, it returns row without any fail. why laravel giving me errors?
This is a setting in laravel/mysql for laravel look in config/database.php.
Set strict mode to false
'connections' => [
'mysql' => [
'strict' => false,
]
Laravel is not giving you the error it's just actually enforcing MYSQL rules. PHPMYADMIN and other tools don't force it so that's why you don't get the error.
The reason laravel is so good, is because you can get rid of writing huge database queries like this.
You should take some time out to really site down and read the documentation for laravel and how eloquent works. You will be surprised how quickly you pick it up, i promise.
Now for a situation such as your self, you have two models.
Post Model
Location Model
In your Posts model you would create a relationship like so
public function location()
{
return $this->belongsTo(Location::class);
}
and in your Location model you would now define a relationship like so
public function post()
{
return $this->hasMany(Post::class);
}
Now in your posts_table you need to ensure you have a location_id integer column.
Now what you can do is get the Location instance you want for example:
//This will give you the row where id = 1
$location = Location::find(1);
Now you can easily do this to access all the posts with that location:
foreach($location->posts as $post){
//Do whatever you want here $post is the object
echo $post->title
}
And the relationship works on the inverse, example:
$post = Post::find(1);
Now because this post belongs to only 1 location you can call it like so
echo $post->location->column_name_in_location_table
Hope this helps kick start your journey to learning laravel!

Issue with "where" in an associated query in Symfony 3

I'm trying to make a "search engine" for my app; the table I want to show, contains two fields which are associated to another tables.
I'm using this query:
Select work from WorkBundle:Work work
where work.client.name like '$search%'
Work, is associated with the tables "user" and "client", I have the associations correctly defined so I don't have to use the inner join statement, but I get the following error:
[Semantical Error] line 0, col 68 near 'nombre like 'fsdf%'': Error: Class WorkBundle\Entity\Work has no field or association named client.nombre
I don't know how to access to the "name" field which is on the "client" table.
Actually I can do the same by using a full inner join query and it works but I can't use it in my app.
I do not know for sure but it seems you cant use selectors like work.client.name. I think it based on doctrine uses "lazy" queries. So you must use table joins in this case.
So it should look smth like that
// work repository
public function findByKeyword($keyword)
{
$qb = $this->createQueryBuilder("w");
$result = $qb
->add('where', $qb->expr()->like("wc.name", ':keyword'))
->leftjoin("w.client", "wc") //or join or innerjoin depends of your case
->setParameters([
'keyword' => $keyword
])
->getQuery()
->getResult()
;
return $result;
}

Laravel Restful Controller ID

So to explain my issue, whenever i am connecting to the database with Laravel it will default search for the id column as "id".
If i name my column jobID for example, i would like to controller to search for "jobID" instead of just "id". I could just change all of my tables ID columns to "id" however this causes issues when you use Laravel's left joins as it will take the latest id column as the actual id column.
Heres my join:
$jobs = Job::leftJoin('occupational_areas', function($join) {
$join->on('jobs.occupationalArea', '=', 'occupational_areas.id');
})->get();
However Restful controller default to "id" and that is what i'm asking, how do i change the default "id" to becomes something more custom like jobID
Try using this left join
$jobs = Job::select('occupational_areas.id as occ_id', 'jobs.id as jobs_id', your required values)
->leftJoin('occupational_areas', 'jobs.occupationalArea', '=', 'occupational_areas.id')
->get();
comment for errors
Turns out the easiest way to do this is by setting:
protected $primaryKey = 'jobID';
Into your model.
I am pretty sure Ronser also had it right with his method. Either will work.
Thanks Ronser!

Yii - Joining multiple tables using active record

I am currently working on a YII application, which I must admit is my first attempt. I am having difficulty mastering the active record component of YII. In particular I would like to join three tables using with().
My mysql tables are as follows:
video_specific
- id (primary key)
- random_id
- user_id
- video_link
- quality (enum, high,low)
video_details
- video_id
- upvote_count
- downvote_count
- timestamp
ladder_videos
- ladder_id
- video_id
ladder_specific
- id
- random_id
- name
- description
- ladder_type
- status
- video_count
Thus after using the gii tool I was give models with the following relationships. Please note that I did not create a model for the ladder_videos table.
In videoSpecific model
'ladderSpecifics' => array(self::MANY_MANY, 'LadderSpecific',
'ladder_videos(video_id, ladder_id)'),
'videoDetails' => array(self::HAS_ONE, 'VideoDetails', 'video_id')
In ladderSpecific model
'videoSpecifics' => array(self::MANY_MANY, 'VideoSpecific',
'ladder_videos(ladder_id, video_id)')
With these relations I thought I could right the following query
$ladders = LadderSpecific::model()->with(
array('videoSpecifics'=>array('select'=>'id,video_link,random_id',
'join'=>'videoDetails')))->findAll();
But I get the following error
CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: Syntax error or
access violation: 1064 You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'videoDetails'
at line 1. The SQL statement executed was: SELECT `t`.`id` AS `t0_c0`, `t`.`random_id` AS
`t0_c1`, `t`.`name` AS `t0_c2`, `t`.`description` AS `t0_c3`, `t`.`ladder_type` AS
`t0_c4`, `t`.`status` AS `t0_c5`, `t`.`video_count` AS `t0_c6`, `videoSpecifics`.`id` AS
`t1_c0`, `videoSpecifics`.`video_link` AS `t1_c3`, `videoSpecifics`.`random_id` AS `t1_c1`
FROM `ladder_specific` `t` LEFT OUTER JOIN `ladder_videos` `videoSpecifics_videoSpecifics`
ON (`t`.`id`=`videoSpecifics_videoSpecifics`.`ladder_id`) LEFT OUTER JOIN `video_specific`
`videoSpecifics` ON (`videoSpecifics`.`id`=`videoSpecifics_videoSpecifics`.`video_id`)
videoDetails
Any ideas why?? Please limit your answers to active record, and not DAO or query builder. Thanks
It would help to review how relations work in Yii.
http://www.yiiframework.com/doc/guide/1.1/en/database.arr
When querying the model, Yii automatically generates the query to fetch the relational data, so you don't have to supply it.
You must therefore supply the name given to your relation.
$ladders = LadderSpecific::model()->with('videoSpecifics')->findAll();
SO the answer was to update the ladderSpecific relations. So once you update them they should like this:
public function relations(){
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'ladderDetails' => array(self::HAS_ONE, 'LadderDetails', 'ladder_id'),
'videoSpecifics' => array(self::MANY_MANY, 'VideoSpecific', 'ladder_videos(ladder_id, video_id)'),
array(self::HAS_ONE, 'VideoDetails', 'video_id'),
);
}
Once you have updated this relation you can do this:
$ladders = LadderSpecific::model()->with(
array('videoSpecifics.videoDetails'=>
array(
'order'=>'videoDetails.upvote_count - videoDetails.downvote_count DESC',
'limit'=>'1'
)))->findAll(array('order'=>'name',));
The only issue is for some reason I can not limit the number of records returned. Once I figure that out I will update my answer. If you have a better way of doing it let me know.

Categories