get data from table and from relative foreign tables in SQL - 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

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().

Is there any way to set multiple LIKE options inside where clause in cakephp 3

I want to retrieve all rows matched on multiple partial prase against with a column. My situation can be explained as following raw sql:
SELECT *
FROM TABLENAME
WHERE COLUMN1 LIKE %abc%
OR COLUMN1 LIKE %bcd%
OR COLUMN1 LIKE %def%;
Here, abc, bcd, def are array elements. i.e: array('abc','bcd','def'). Is there any way to write code passing this array to form the above raw sql using cakephp 3?
N.B: I am using mysql as DBMS.
probably you can use Collection to create a proper array, but I think a foreach loop will do the job in the same amount of code. So here is my solution supposing $query stores your Query object
$a = ['abc','bcd','def'];
foreach($a as $value)
{
$or[] = function ($exp, $q) use ($value) {
return $exp->like('column1', '%'.$value.'%');
};
}
$query->where(['or' => $or]);
you could also use orWhere() but I see it will be deprecated in 3.6

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

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;

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.

Using with and together in Yii

I have a grid with paging which displays client data.
Let's say I have a table Client with name, lastName and address in it, a table Phone_Number which has phone numbers for each of the rows in Client and a table Adress which has adresses for each client. So each Client HAS MANY Phone_Numbers and HAS MANY Adresses.
The point is I'm trying to set a limit to the grid's store read.
So let's say I set limit = 2. The grid should display only 2 rows per page (2 clients).
The problem is that if, for example, client1 has two phone numbers, the query will bring two rows, making the grid display only one client. I am aware that setting together=>false in the query will solve this. But I'm getting an unknown column error whenever I set together=>false.
Here's the code I'm using....
Client::model()->with(
'clientPhoneNumbers',
'clientPhoneNumbers'.'PhoneNumber',
'clientAddresses',
'clientAddresses'.'Address'
)->findAll(array(condition=>(('Address.s_street_name LIKE :queryString') OR ('PhoneNumber.n_number LIKE :queryString')), params=>$params, order=>$order, limit=>$limit,together=>false));
If I do this, I get an error like: Column not found: Address.s_street_name . However, if I set together=>true, it works just "fine".
I found a solution to this problem by doing the query like this....
$with = array(
'clientPhoneNumbers',
'clientPhoneNumbers'.'PhoneNumber'=>array(condition=>('PhoneNumber.n_number LIKE :queryString'), params=>array(':queryString'=>$queryString)),
'clientAddresses',
'clientAddresses'.'Address'=>array(condition=>('Address.s_street_name LIKE :queryString'), params=>array(':queryString'=>$queryString))
);
Client::model()->findAll(array(with=>$with, order=>$order, limit=>$limit,together=>false));
The problem is that if I do it like this, the condition is something like this
(('Address.s_street_name LIKE :queryString') AND ('PhoneNumber.n_number LIKE :queryString'))
and I need it to be like this
(('Address.s_street_name LIKE :queryString') OR ('PhoneNumber.n_number LIKE :queryString')).
Any ideas ?
Keep in mind that the names of the relations and tables are not the actual names. The models and relations where created using Gii
Hmm.. this is how I would try it.
<?php
$criteria=new CDbCriteria;
$criteria->with = array('clientPhoneNumbers', 'clientAddresses');
$criteria->together = true;
$criteria->addCondition(array('Address.s_street_name LIKE :queryString', 'PhoneNumber.n_number LIKE :queryString'), 'OR');
$criteria->params = array(':queryString' => $queryString);
$criteria->limit = $limit;
$criteria->order = $order;
$result = Client::model()->findAll($criteria);
?>
Also, I think this describes a case similar to yours. Note that he/she is updating the condition parameter explicitly, but IMO doing it with the addCondition method is more readable.
use criteria with join statement.
public function test()
{
$criteria=new CDbCriteria;
$criteria->alias = 'i';
$criteria->compare('id',$this->id);
.........
.........
$criteria->join= 'JOIN phoneNUmbers d ON (i.id=d.id)';
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'sort'=>array(
'defaultOrder'=>'clients ASC',
),
));
}
Alternately use DAO to prepare and execute your own query and return data in the format you wish.
Or you can use CSQLDataProvier. the last 2 options give you more control over the SQL statement