How to write database/SQL query in Yii2, with and without a model - sql

I have a table with multiple column and I want to return a column name using another column name as search criteria. How do I achieve this in yii2?
Below is sample code, normal sql should be:
$name = SELECT type_name FROM ProductTable WHERE type_id = 1;
echo $name;
This should return the value of the column type_name where the value of the column type_id equals 1. I tried this, but it doesn't work
$type_name = ProductTable::find()->where(['type_id' =>$model->type_id]);
$type_name = Product::find(['type_name'])->where(['type_id' =>$model->type_id]);
I also tried this, but I guess it was wrong
I hope my question is clear enough and any help will he appreciated

and u could also use createCommand!
$name = \Yii::$app->getDb()->createCommand("SELECT type_name FROM ProductTable WHERE type_id=:typeId", ['typeId'=>$model->type_id])->queryAll();

For a general introduction to Yii2's ActiveRecord, see the guide: http://www.yiiframework.com/doc-2.0/guide-db-active-record.html
If you want the complete row and have a model, you're just missing a one():
Product::find()->where(['type_id' =>$model->type_id])->one();
If you do have a Model defined and just want a single value, try:
Product::find()->select('type_name')->where(['type_id' =>$model->type_id])->scalar();
Which basically generates an ActiveQuery via the model, and changes it to return only the first column in the first row of matched results.
If you do NOT have a model, you could also generate a normal query without ActiveRecord usage (http://www.yiiframework.com/doc-2.0/yii-db-query.html)
$name = (new Query())->select('type_name')
->from('ProductTable')
->where(['type_id' =>$model->type_id])
->scalar();

I assume you generated ProductTable by using Gii module.
Also, if type_id column is a primary key:
$product = ProductTable::findOne($model->type_id);
if($product !== null) { $product->typeName /*... read value ...*/}
or to get all records
$products = ProductTable::findAll($model->type_id); //match all records.
for any other column use the following syntax instead:
$product = ProductTable::findOne(['type_id' => $model->type_id]);

Use following code to get type_name
$PTable=ProductTable::find()->select('type_name')->where(['type_id' =>$model->type_id])->one();
echo $PTable->type_name;

Related

TYPO3 $query->in('valOne,valTwo,valThree', $arrayTwo)

I have a query in my repository which gets all product by categories and contentTypes.
I am looking for a query like this:
$query = $this->createQuery();
$constraint = $query->in('category', $categories);
if (!empty($contentType)) {
$results = $query->matching(
$query->logicalAnd(
$constraint, $query->in('contentType', $contentType)
)
)
->setLimit((int)$limit)
->setOffset((int)$offset)
->execute()
->toArray();
It works well if 'containType' contains just a single id as string, e.g '261'.
But if it is a string with multiple id's it looks like '261,284,291' and the query does not work longer.
I hope you got all information. Let me know if not :)
You can use GeneralUtility::trimExplode() or in your case probably more specific GeneralUtility::intExplode() to turn the $contentType CSV value into an array of values suitable for QueryInterface::in().

using .where with .find

I am wondering how I can use where cause with the ActiveRecord find method.
Here is the code I am using:
Supplier.joins(:products).find(params[:id]).where('suppliers.permalink = ? AND variants.master = ?', params[:id], TRUE)
which gives me:
undefined method `where' for #<Supplier:0x007fe49b4eb330>
Supplier.joins(:products).find(params[:id]).where('suppliers.permalink = ? AND variants.master = ?', params[:id], TRUE)
What you're doing here is finding the first record with the id contained in params[:id], then trying to run a where statement on that single record. where only works when run against the model itself.
The confusing part here is that you are using params[:id] both for the primary key (find searches the id field) but then also comparing it to the permalink column in the where clause.
To explain the usage of both methods:
find will search for result(s) from the table, matching the argument you provide it to the id field. You can pass in multiple id's and this method is mostly used to select a row that you know exists, by id. Most commonly it is used with a single id and returns a single instance.
where is used to find all results from the table that match the clause and return a collection of records. You can then refine these results or select one, for example by using .first:
Supplier.joins(:products).where('suppliers.permalink = ? AND variants.master = ?', params[:permalink], true).first
(Note that you're using joins(:products) but then querying variants table. Is this incorrect?)
Supplier.joins(:products).where('suppliers.permalink = ? AND variants.master = ?', params[:id], TRUE).find(params[:id])

get data from table and from relative foreign tables in SQL

Hi have a text search input that looks for matching records in the DB and gets all the data from a table:
let's say like this:
$q = Input::get('items');
$q = "\"" . "($q)" . "\"";
$items = DB::table('my_items')->whereRaw(
'MATCH(item_name) AGAINST(? IN BOOLEAN MODE)',
array($q)
)->get();
So I get all the items in the DB from my textsearch, then I send the result as json to some script that updates my page with the items:
return Response()->json($items);
The relations are:
My_item:
public function brand(){
return $this->hasOne('App\Brand', 'id', 'brand_id');
}
Brand:
public function My_item(){
return $this->belongsToMany('App\My_item');
}
Now the problem here is that in 'my_items' table I have some data as IDs that reference foreign tables.
For example I will have a 'brand_id' that for example references a 'brands' table where I can have information regarding the brand.
So for example I could have brand_id = 3 that means 'Microsoft' in my brands table (id = 3, name = microsoft).
Now what I need to do is not only passing the brand_id to my view but also the actual information (name), in this case Microsoft so that I can put that info in the item description.
But, how can I get that information before sending with that query? Is there some sort of flag I can use in the query like $items = DB::table bla bla with foreign?
this way works, DB:: method is dropped for:
$items = My_item::with('brand')->where('item_name', 'LIKE', "%$q%")->get();
this one doesn't:
DB::table('my_items')::with('brand')->where('item_name', 'LIKE', "%$q%")->get();
First of all, you can simplify your search query to something like this:
My_item::where('item_name', 'LIKE', "%$q%")->get();
Now, assign relations the relation to your other tables in your Models. Then you can get all information using the following syntax:
My_item::with('brand')->where('item_name', 'LIKE', "%$q%")->get();
Read more about relations here: https://laravel.com/docs/5.1/eloquent-relationships

pdo print info using given value pdo

function getCars($memebrNo) {
// STUDENT TODO:
// Change lines below with code to retrieve the cars of the member from the database
$stmd=$dbh->prepare('SELECT name FROM PeerPark.Car JOIN PeerPark.Member WHERE memberNo=:memberNo');
$stmd->bindParam(':memberNo', $memberNO, PDO::PARAM_STR);
$stmd->execute;
$result=$stmd->fetchAll(PDO::FETCH_COLUMN);
var_dump($result);
these are my codes, but i want to print like the following, besides can someone tell me am i using the memberNo given in function the right way? Thanks
$results = array(
array('car'=> 'Gary'),
array('car'=> 'Harry' )
);
To get a result like that, your query should be:
$stmd=$dbh->prepare('SELECT name AS car FROM PeerPark.Car JOIN PeerPark.Member WHERE memberNo=:memberNo');
and then you should fetch the results with:
$result = $stmd->fetchAll(PDO::FETCH_ASSOC);
PDO::FETCH_COLUMN returns an index array containing all the values of the column. PDO::FETCH_ASSOC returns a 2-dimensional array where each element is an associative array mapping the column names to their values.

SELECT MAX query returns only 1 variable + codeigniter

I use codeigniter and have an issue about SELECT MAX ... I couldnot find any solution at google search...
it looks like it returns only id :/ it's giving error for other columns of table :/
Appreciate helps, thanks!
Model:
function get_default()
{
$this->db->select_max('id');
$query = $this->db->getwhere('gallery', array('cat' => "1"));
if($query->num_rows() > 0) {
return $query->row_array(); //return the row as an associative array
}
}
Controller:
$default_img = $this->blabla_model->get_default();
$data['default_id'] = $default_img['id']; // it returns this
$data['default_name'] = $default_img['gname']; // it gives error for gname although it is at table
To achieve your goal, your desire SQL can look something like:
SELECT *
FROM gallery
WHERE cat = '1'
ORDER BY id
LIMIT 1
And to utilise CodeIgniter database class:
$this->db->select('*');
$this->db->where('cat', '1');
$this->db->order_by('id', 'DESC');
$this->db->limit(1);
$query = $this->db->get('gallery');
That is correct: select_max returns only the value, and no other column. From the specs:
$this->db->select_max('age');
$query = $this->db->get('members');
// Produces: SELECT MAX(age) as age FROM members
You may want to read the value first, and run another query.
For an id, you can also use $id = $this->db->insert_id();
See also: http://www.hostfree.com/user_guide/database/active_record.html#select
CodeIgniter will select * if nothing else is selected. By setting select_max() you are populating the select property and therefore saying you ONLY want that value.
To solve this, just combine select_max() and select():
$this->db->select('somefield, another_field');
$this->db->select_max('age');
or even:
$this->db->select('sometable.*', FALSE);
$this->db->select_max('age');
Should do the trick.
It should be noted that you may of course also utilize your own "custom" sql statements in CodeIgniter, you're not limited to the active record sql functions you've outlined thus far. Another active record function that CodeIgniter provides is $this->db->query(); Which allows you to submit your own SQL queries (including variables) like so:
function foo_bar()
{
$cat = 1;
$limit = 1;
$sql = "
SELECT *
FROM gallery
WHERE cat = $cat
ORDER BY id
LIMIT $limit
";
$data['query'] = $this->db->query($sql);
return $data['query'];
}
Recently I have been utilizing this quite a bit as I've been doing some queries that are difficult (if not annoying or impossible) to pull off with CI's explicit active record functions.
I realize you may know this already, just thought it would help to include for posterity.
2 helpful links are:
http://codeigniter.com/user_guide/database/results.html
http://codeigniter.com/user_guide/database/examples.html