Laravel 4.2 generate sub query like this - laravel-4

I want to do like this in Eloquent way.
select * from `documents` where (`id` in (select `related_id` from
`common_data` where `meta_key` = 'meta_key_name' and `meta_value` =
'1') or `created_by` = '1')
Thanks for any answer.

Try it
$data = Document::where(function($query){
$query->whereRaw(" id in (select `related_id` from `common_data` where `meta_key` = 'meta_key_name' and `meta_value` ='1')")
->orWhere('created_by',1);
})->get();

Related

Codeigniter count_all_results() and result() with group_by, join, where vs

I want to do query both result and count with group_by.
$id= 2;
$limit = 10;
$offset = ($id - 1) * $limit;
$this->db->group_by('BE.etiket_id');
$this->db->from('bulten_icerigi_etiketler as BE');
$this->db->join('etiketler as E', 'BE.etiket_id=E.id', 'left');
$this->db->join('bulten_icerigi as BI', 'BE.bulten_id=BI.id', 'left');
$count = $this->db->count_all_results('', false);
$this->db->limit($limit, $offset);
$this->db->order_by('E.adi');
$results = $this->db->get()->result();
However, I have error
Error Number: 1054
Unknown column 'tbl_`E.adi' in 'field list'
Can I use count_all_results() and result() together ?
Thank you.
You can't group by columns which you didn't selected in select.
Try to use E.adi and E.id instead of BE.etiket_id in your group by.
Your query should looks like:
SELECT
COUNT(*) as count,
tbl_E.adi,
tbl_E.id
FROM tbl_bulten_icerigi_etiketler as BE
LEFT JOIN tbl_etiketler as E ON BE.etiket_id=E.id
LEFT JOIN tbl_bulten_icerigi as BI ON BE.bulten_id=BI.id
GROUP BY tbl_E.adi, tbl_E.id // here you need to change
ORDER BY tbl_E.adi
$this->db->group_by(array("E.adi", "E.id"));

subquery inside orWhere in laravel

I need assistance to build up the query like below in laravel:
SELECT *
FROM table t
WHERE t.a = 1
OR (t.a=0
AND t.id IN (
SELECT o.a_id
FROM other_table o
WHERE o.x > 3
)
);
You could try to build your exact current query, and in fact it might even be the most efficient to write it. But, if we rephrase your query using a left join, it becomes somewhat easier to express in Laravel code.
SELECT *
FROM your_table t
LEFT JOIN other_table o
ON t.id = o.a_id AND o.x > 3
WHERE
t.a = 1 OR
(t.a = 0 AND o.a_id IS NOT NULL);
This would translate to the following Laravel code:
$result = DB::table('your_table t')
->leftJoin('other_table o', function($join) {
$join->on('t.id', '=', 'o.a_id');
$join->on('o.x', '>', '3');
})
->where('t.a', '=', '1')
->orWhere(function($query) {
return $query->where('t.a', '=', '0')
->whereNotNull('o.a_id')
})
->get();

I want to pass this query to Eloquent in laravel

I'm trying to make a query with eloquent, I try to get all the users who have one or more ads, taking into account that it is a one to many relationship (users to ads).
This query in general does what I want, but I do not know if it is well done and also how to pass it to Eloquent through the User model.
SELECT users.id, COUNT( anuncio.id ) AS 'total' FROM users
INNER JOIN anuncio ON users.id = anuncio.usuario_id WHERE
(SELECT COUNT( * ) FROM anuncio WHERE anuncio.usuario_id = users.id) >0
GROUP BY users.id ORDER BY total DESC
I have tried several ways that only return Builder to me.
For example:
$listas = new User;
$listas = $listas->join('anuncio','users.id','=','anuncio.usuario_id');
$listas = $listas->select(array('users.*', DB::raw('COUNT(anuncio.id) AS total')));
$listas = $listas->where(function($query) use ($listas){
$query->select(DB::raw('COUNT(anuncio.usuario_id)'))
->where('anuncio.usuario_id','=','users.id')
->groupBy('anuncio.usuario_id');
},'>','0');
$listas = $listas->orderBy('total','DESC')->paginate(48);
By any suggestion I will be very grateful.
Try with this
$listas = User::join('anuncio','users.id','=', 'anuncio.usuario_id')
->select('users.id',DB::raw("count(anuncio.id) as total"))
->groupby('users.id')
->having('total', '>', '0')
->orderby('total', 'desc')
->get();
Just use left join for this.
$users = DB::table('users')
->leftJoin('anuncio', 'users.id', '=', 'anuncio.usuario_id')
->get();
So Left Join will only select those result which has any match in anuncio table.

left join with ActiveRecord (yii2)

I tried to send SQL request with LEFT JOIN but it doesn't display data from table2 table.
public static function top($limit)
{
return self::findBySql("
SELECT * FROM table 1 g1
LEFT JOIN table2 s1
ON (g1.id = s1.g_id AND s1.id = (
SELECT MAX(id)
FROM table2 s2 WHERE s2.g_id = g1.id
))
LIMIT :limit",
[':limit' => $limit]
)->all();
}
It seems you are adding this function to the model and self represents the model itself.
Yii will not return results from another table and will be limited to the model only if you are calling the find on a model, instead you need to use a db query as below:
$query = new \yii\db\Query;
$query->select('*')
->from('table 1 g1')
->leftJoin('table2 s1', 's1.g_id AND s1.id = (SELECT MAX(id) FROM table2 s2 WHERE s2.g_id = g1.id')
->limit($Limit);
$command = $query->createCommand();
$resp = $command->queryAll();
The correct SQL query is
SELECT * FROM table 1 g1
LEFT JOIN table2 s1
ON g1.some_field = s1.some_field
where g1.some_field = s1.some_field are the fields that define the join.
I have working code something like...:)
with user and user_friend_list
$query = new Query;
$query ->select(['user.id AS user_id', 'user_friend_list.id'])
->from('user')
->innerJoin('user_friend_list', 'user.email = user_friend_list.email');
$command = $query->createCommand();
$data = $command->queryAll();
foreach($data as $datakey)
{
//echo $datakey['id'];
$friendfind = UserFriendList::findOne($datakey['id']);
$friendfind->is_app_using_user_id=$datakey['user_id'];
$friendfind->save();
}

Using subquery in Doctrine 1.2

I'm having alot of trouble using a subquery in an update statement in doctrine 1.2
I want to set a field to the result of a subquery, but it seems impossible.
This is what i tried sofar.
$query = Doctrine_Query::create()->from('Users_Model_Book b');
$subSelect = $query->createSubquery()->select('ROUND(SUM(br.rating) / COUNT(br.id))')->from('b.BookRating')->where('b.BookRating.book_id = b.id');
$query->update()->set('bookrating', '('.$subSelect->getDql().')')->where('b.id = ?', $this->id)->getRawSql();
Will give 'Unknown component alias br'
$q = new Doctrine_RawSql();
$q ->addComponent('b', 'Users_Model_Book')
->addComponent('br', 'Users_Model_BookRating')
->update('b')
->set('b.bookrating', 'ROUND(SUM(br.rating) / COUNT(br.id)')
->where('b.id = ' . (bool) $this->id);
echo $q->getSqlQuery();
Will return SELECT b.id AS b_id, br.id AS br_id FROM b WHERE b.id = 1
Anybody that can help me?

Resources