Why am I getting this:
An error occurred
Application error
Exception information:
Message: Select query cannot join with another table
while trying to join two tables?
I have this line code inside my model which extends Zend_Db_Table_Abstract
public function getProjects() {
$select = $this->select()
->from(array('sub' => $this))
->join(array('main' => 'main_projects'), 'main.mai_id = sub.mai_id');
return $this->fetchAll($select);
}
And I use this in my controller: $this->view->entries = $this->sub_projects->getProjects();
Why the hell I get this error? I just want to make a simple join
SELECT sub.*, main.mai_title FROM sub_projects AS sub INNER JOIN main_projects AS main ON sub.mai_id = projects.mai_id;
enter code here
I think here is your solution and explanation : http://www.mail-archive.com/fw-general#lists.zend.com/msg24553.html
Another solution here : Translating a query to use Zend_Db_Select
Related
I have two related tables, posts and hidden_posts, where posts.id corresponds to hidden_posts.post_id.
In my posts model I have this relation to return a record if the post should be hidden:
public function getHiddenPosts()
{
return $this->hasOne(HiddenPost::className(), ['post_id' => 'id']);
}
Now I need to return all posts that are NOT hidden. So I am looking for the equivalent of this pseudo code:
return $this->hasNone(HiddenPost::className(), ['post_id' => 'id'])->all();
Which is saying, "show me all posts that are not in the hidden_posts table".
So does this use an outer join query or is there a statement that I can't find do do this in one line?
You can do it this way. Get all posts that are not listed in Hidden table:
$posts = Post::find()
->andFilterWhere(['not in',
'post.id',
HiddenPost::find()
->select(['hidden_post.post_id'])
->all();
In any case, it is best to proceed from the raw SQL statement. Write a statement that satisfies your results and transfer it to ActiveRecord query.
Post items could be retrieved using an inner join
$res = Post::find()
->select('post.*')
->innerJoin('hdn_post', '`post`.`id` = `hdn_post`.`post_id`')
->all();
It could be good practice using yii2 owned function instead of adding queries inside the model such as using select queries in your model.
Instead you can use ORM functions in yii2 has already done by gii inner functions created for to make u=your work easy.
Add * #property YourModel $hidden_post
and inside this model add you post_id such as ( * #property integer $post_id ) to create relation.
public function getHiddenPosts($hidden_post) {
return $this->find()->joinWith('hidden_post')
->where(['hidden_post' => $hidden_post])
->all();
}
You could retrive the Post items using an inner join
$posts = Post::find()
->select('post.*')
->innerJoin('hidden_post', '`post`.`id` = `hidden_post`.`post_id`')
->all();
for not hidden then use left join and check for null result of related table
$posts = Post::find()
->select('post.*')
->leftJoin('hidden_post', '`post`.`id` = `hidden_post`.`post_id`')
->where('ISNULL(`hidden_post`.console_id)')
->all();
So I am trying to make an ajax call with an entity Id and query a data of that. As far as I know, if an url is such abc.com/xyz/123 then it will hit xyz controller with 123 as parameter and I did that but it says, "An Internal Error Has Occurred". The error log states the headline of this thread.
The method is:
public function fetch($order_details_id)
{
$sql = "SELECT
orders.id
, ROUND(SUM(rolls.weight),2) as produced_qty
FROM orders
LEFT JOIN order_details ON order_details.buyer_order_id = orders.id
LEFT JOIN knitting_plans ON knitting_plans.buyer_order_detail_id = order_details.id
LEFT JOIN jobcards ON jobcards.knitting_plan_id = knitting_plans.id
LEFT JOIN machines ON machines.id = jobcards.machine_id
LEFT JOIN rolls ON rolls.jobcard_id = jobcards.id
WHERE order_details.id = $order_details_id
ORDER BY orders.id";
$data = $this->BuyerOrder->query($sql);
$this->set('data', $data);
}
What's wrong in this code?
URL: /buyerOrders/fetch/52629
Since my objective is to return the result in html/json format. Let me know if I could return in a better way.
load model before query execution
It's trying to call query on null, the only query call here is on $this->BuyerOrder, so it's clear that it unable to find BuyerOrder.
So load model
$this->loadModel('BuyerOrder');
I am trying to implement following join query
SELECT * from users as u
LEFT JOIN `table1` as ou
ON ou.user_id = u.id
LEFT JOIN table2 as o
ON o.id = ou.orid
LEFT JOIN table3 as p
ON o.pra_id = p.id;
with my laravel model so i create a function named alldata() in my user model with following code
public function alldata()
{
return $this
->leftjoin('table1','users.id','=','table1.user_id')
->leftjoin('table2','table1.orid','=','table2.id')
->leftjoin('table3','table2.pra_id','=','table3.id');
}
now when i try to access the data by $gd = User::find(1)->getall() it returns results with all the table
but when i try to acces $gd = User::all()->alldata() it gaves error mathod not found
how can i resolve this
thanks
The User::find(1) function returns an single instance of the object (or NULL if not found).
The User::all() function returns a Collection of all User objects.
You need to create a query then get() the results as follows...
public static function alldata()
{
return self::query()
->leftjoin('table1','users.id','=','table1.user_id')
->leftjoin('table2','table1.orid','=','table2.id')
->leftjoin('table3','table2.pra_id','=','table3.id')
->get();
}
Assuming your your alldata() method is in the User class you can call the function with the following code:
User::alldata();
Laravel has a excellent database relationship system which is most defiantly worth looking at. It would make queries like the one above much simpler...
https://laravel.com/docs/5.1/eloquent-relationships
I have been trying to convert a right join query to left join query in order to use it inside laravel query builder. Here is my Sql statement and it result wich works flawlessly
select `weekday`.`name`, `open_time`, `close_time`
from `schedule`
join `restaurants_has_schedule` on `schedule`.`id` = `restaurants_has_schedule`.`schedule_id`
and `restaurants_has_schedule`.`restaurants_id` = 1
right join `weekday` on `weekday`.`id` = `schedule`.`weekday_id`
ORDER BY `weekday`.`id`
|------
|name|open_time|close_time
|------
|Domingo|NULL|NULL
|Lunes|NULL|NULL
|Martes|NULL|NULL
|Miercoles|NULL|NULL
|Jueves|14:11:51|14:11:51
|Vienes|09:11:21|17:00:00
|Sábado|NULL|NULL
but when convert It to left join it stop working, displaying me the same data for every single restaurants_id. This is my left join statement.
select `weekday`.`name`, `open_time`, `close_time`
from `weekday`
left join `schedule` on `weekday`.`id` = `schedule`.`weekday_id`
join `restaurants_has_schedule` on `schedule`.`id` = `restaurants_has_schedule`.`schedule_id`
and `restaurants_has_schedule`.`restaurants_id` = 1
ORDER BY `weekday`.`id`
What am I doing wrong? Is There another alternative? Thak you in advance
Try use Laravels Eloquent ORM, which handles relationships really cool! no need anymore to concat or write sql-queries
See here about: Laravels Eloquent ORM & Schema Builder
Or maybe about orm's in general, you should really give it a try:
Object Role Modeling
Object Role Modeling
Example from Laravel doc:
One Post may have many comments
One to many:
class Post extends Eloquent {
public function comments()
{
return $this->hasMany('Comment');
}
}
Where 'Comment' is the model.
The "reverse" to define:
class Comment extends Eloquent {
public function post()
{
return $this->belongsTo('Post');
}
}
Where 'Post' is the model.
And then as query:
$comments = Post::find(1)->comments; //by Primary Key
Or
$comments = Post::where('somefield', '=', 'somevalue')->comments->get();
....Really cool, for many to many see the docs#Laravels Eloquent ORM
How I can write the query
SELECT *
FROM doc_docs dd
JOIN doc_access da
ON dd.id=da.doc_id
AND da.user_id=7
with CDbCriteria syntax?
You actually cant completely write that since you have to apply the criteria to an activerecord model to obtain the primary table, but assuming you have a DocDocs model you can do it like this:
$oDBC = new CDbCriteria();
$oDBC->join = 'LEFT JOIN doc_access a ON t.id = a.doc_id and a.user_id = 7';
$aRecords = DocDocs::model()->findAll($oDBC);
Although it might be a lot easier if you give your DocDocs model a relation with doc_access, then you don't have to use the dbcriteria:
class DocDocs extends CActiveRecord
{
...
public function relations()
{
return array('access' => array(self::HAS_MANY, 'DocAccess', 'doc_id');
}
...
}
$oDocDocs = new DocDocs;
$oDocDocs->id = 7;
$aRecords = $oDocDocs->access;
Should give you a fairly good idea how to start...