Active record of not in - activerecord

$this->db->query('DELETE FROM default_model WHERE cat_id NOT IN (SELECT id FROM default_category)');
the active record format for this query
$query = $this->db->select('id')
->get('category')->result();
$this->db->where_not_in('cat_id',$query )
->delete('model');
I tried a lot but could not do it. How to pass $query

The query results are returned as standard objects. Therefore you need to fetch the ids from the returned objects in a non associative array before passing that array to the delete query.
Like this:
$result = $this->db->select('id')->get('category')->result();
$ids = [];
foreach($result as $result)
$ids[] = $result->id;
$this->db->where_not_in('cat_id', $ids)->delete('model');

Related

How to get string value using eloquent query

I am trying to execute a query using eloquent, however it returns me an array. What I want is to only get the string value of my query.
This is what I get
[{"name":"hey"}] [{"name":"sdasdasd"}]
Here's my eloquent query:
$categoryName = Category::select('name')->where('id', request('category'))->get();
$subCategory = Subcategory::select('name')->where('id', request('subCat'))->get();
as per the Laravel Docs
Retrieving A Single Row / Column From A Table
If you just need to retrieve a single row from the database table, you may use the first method. This method will return a single stdClass object:
$user = DB::table('users')->where('name', 'John')->first();
echo $user->name;
If you don't even need an entire row, you may extract a single value from a record using the value method. This method will return the value of the column directly:
$email = DB::table('users')->where('name', 'John')->value('email');
so in your example maybe you need to do something like the following :
$subCategory = Subcategory::select('name')->where('id', request('subCat'))-> first();
echo $subCategory->name;
There are so many ways to achive your goal.
Solutions
Use pluck().
$categoryName = Category::select('name')
->where('id', request('category'))
->pluck()
->first();
Use model properties.
$categoryName = Category::find(request('category'))
->name;
If you take only name then follow the below code.
$categoryName = Category::where('id', request('category'))->first()->name;
$subCategory = Subcategory::where('id', request('subCat'))->first()->name;
echo $categoryName;
echo $subCategory;
If you take all columns in a row follow the below code:
$categoryName = Category::where('id', request('category'))->first();
$subCategory = Subcategory::where('id', request('subCat'))->first();
echo $subCategory->name;
echo $categoryName->name;
I hope this i may help you.Try this.
You can get the answer using
$name = DB::table('Category')->where('id','=',request('category'))->pluck('name')->first();
echo $name;
$name = Category::select('name')->where('id', request('category'))->take(1)->orderBy('id','asc')->first()->name;
echo $name;
OR
echo Category::select('name')->where('id', request('category'))->take(1)->orderBy('id','asc')->first()->name;

get all rows in single query with multiple id

I have a asset_request table with fields id and request_id.
I want to select multiple rows with specific ids.
$ids = $request->ids // 5,6
I want to select only rows with ids of 5 and 6 in request table
$ids = $request->ids;
$asset_request = asset_request::whereIn('id',array($ids))->first(); //gets only 6th row.
I need to get all rows matching the given ids.
To clarify after a chat discussion with the Op:
The Op was passing back a string request, therefore, the Op needed to change the following:
$id = $request->id;
$ids = str_split(str_replace(',', '', $id));
$asset_request = asset_request::whereIn('id', $ids)->get();
First you are calling the first method which will return only the first row matched.
You need to call get method to get all rows matched.
Secondly if you are sending ids as a comma separated string you need to convert it to array using explode.
$ids = $request->ids;
$asset_requst = asset_request::whereIn('id', explode(",", $ids))->get();
DB::table('asset_request')
->whereIn('id', (array) $request->ids)
->get();
or
TableModel::whereIn('id', (array) $request->ids)->get();

Only one row is returned using where in with comma seperated value in Laravel raw query

I am developing a php project using Laravel 5.2. In my app I am retrieving records from database using manual query. But I am having a problem with retrieving records by using where in statement with csv.
Example how I am retrieving
$csv = "1,3,5";
$sql = "SELECT * FROM `items` WHERE `id` IN (?)";
$rows = DB::select($sql,[$csv]);
As you can see above I am retrieving three rows. But it returns only one row where id is 1. Why is that?
You can't do it like that. Each entry in your csv is a separate parameter, so for your code you would actually need IN (?, ?, ?), and then pass in the array of values. It would be pretty easy to write the code to do this (explode the string to an array, create another array of question marks the same size, put it all together).
However, you are using Laravel, so it would be easier to use the functionality Laravel provides to you.
Using the query builder, you can do this like:
$csv = "1,3,5";
// turn your csv into an array
$ids = explode(",", $csv);
// get the data
$rows = DB::table('items')->whereIn('id', $ids)->get();
// $rows will be an array of stdClass objects containing your results
dd($rows);
Or, if you have an Item model setup for your items table, you could do:
$items = Item::whereIn('id', $params)->get();
// $items will be a Collection of Item objects
dd($items);
Or, assuming id is the primary key of your items table:
// find can take a single id, or an array of ids
$items = Item::find($params);
// $items will be a Collection of Item objects
dd($items);
Edit
If you really want to do it the manual way, you could use a loop, but you don't need to. PHP provides some pretty convenient array methods.
$csv = "1,3,5";
// turn your csv into an array
$ids = explode(",", $csv);
// generate the number of parameters you need
$markers = array_fill(0, count($ids), '?');
// write your sql
$sql = "SELECT * FROM `items` WHERE `id` IN (".implode(',', $markers).")";
// get your data
$rows = DB::select($sql, $ids);

Doctrine create subquery with bound params

I am trying to construct a query that will basically pull all entries whose id's have 2 particular entries in another table so I am trying the below:
$query = $this->createQuery('e');
$subquery1 = $query->createSubquery('sea')
->select('sea.entry_id')
->from('Table sea')
->addWhere('sea.form_element_id = ?', $element)
->addWhere('sea.answer = ?', $answer)
->getDQL();
$subquery2 = $query->createSubquery('sea2')
->select('sea2.entry_id')
->from('Table sea2')
->addwhere('sea2.form_element_id = ?', $element2)
->addWhere('sea2.answer = ?', $answer2)
->getDQL();
$query->addWhere('e.id IN ?', $subquery1)
->addWhere('e.id IN ?', $subquery2);
return $query->execute();
However this is gives me an error on bound params.
What is the correct ways of constructing such subqueries?
NOTE that if I dont bind the params in the subqueries it works fine.
$nestedQuery = " id IN (SELECT sea.entry_id from table sea where sea.form_element_id = ? and sea.answer = ?) "
. " and id IN (SELECT sea2.entry_id from table sea2 where sea2.form_element_id = ? and sea2.answer = ?)";
return $this->findBySql($nestedQuery, array($param1, $param2, $param3, $param4));
That obviously returns a doctrine collection but you can do getFirst or loop through the returned objects or even use the Hydrator to get an array!

Get values from a doctrine collection with composite key

4 for on on my applications with Doctrine.
In there I'm using the following doctrine command to retrieve person object collection
//query
$people = $q->execute();
This return 20 objects. The primary key of the person object is a composite key with three attributes. Those are
id
department_id
name
I need to get person objects by searching in it as follows.
$id = 10;
$department_id = 1;
$name = "abc";
$people->get($id, $department_id, $name);
But this doesn't work and not give correct results. I tried with this and it gives null results which seems my collections primary key is not set.
$people->getKeyColumn();
I don't want to go through a foreach loop in collection and process it because when I deal with about 500 people, it slow down my application.
Can some one help me with this issue to get values from a doctrine collection.
Can you use something like this?
$people = Doctrine::getTable('Persons')
->createQuery()
->where('id = ? AND department_id = ? AND name = ?', array($id, $department_id, $name))
->execute();
It will get you a DoctrineCollection already filtered by the parameters provided.
'Persons' here is a Doctrine model name, not a table name from mySQL.
You can also use Doctrine's magic finders findBy*():
$people = Doctrine_Core::getTable('Persons')
->findByIdAndDepartmentIdAndName($id, $department_id, $name);

Resources