Laravel Eloquent : Get object from database using JSON column key - php

I tried to use the following code to retrieve an entire subscription object from my subscription table using the testId column.
testId column is delclared as "json" type but in reality, the content of this column is an array with a single string as follow :
["51602a95-73d1-4c24-b3b3-eee288b427e4"]
I tried to get the subscription object with this code but ot doesn't work. How can i adpat this piece of code to get the subscription object by searching the value of testId into the array ?
function getSubscriptionByTestId($testId) {
$subscription = Subscription::where('testId', $testId)->first();
return $subscription;
}

If all the values are like ["51602a95-73d1-4c24-b3b3-eee288b427e4"] depending on your database engine you could use:
$subscription = Subscription::where('testId','like', "%$testId%")->first();

You can try the following, using a raw query. I'm not yet sure how to handle this with Eloquent, but will investigate further.
return DB::select(
"SELECT * FROM subscription
WHERE testId->\"$[0]\" = \"{$testId}\""
);

Related

Laravel mySQL view return by specific ID

So I am quite new to Laravel, and I have a situation, where I am trying to gather data from a pivot table (contains 2 foreign keys only) in order to retrieve data from other tables.
Before everything, I'd like to note, that word "campaign" is the same as "box". Simply it differs in database and front.
I have multiple boxes, that contains specific gifts.
I have set the URL of the box to be something as such: http://127.0.0.1:8000/box/1
http://127.0.0.1:8000/box/2
etc..
I have done so, by simply using a button with the {id}:
View the box
My plan is, to print out only that specific boxes gifts (right now, all boxes print out all gifts).
I have tried to use the ->where option within my function, although, it seems that I can't try equaling to the campaigns ID.
Incorrect code:
function box(){
$data = array(
'list'=>DB::table('campaigns_gifts')
->join('gift_items', 'gift_items.id', '=', 'campaigns_gifts.gift_foreignK')
->select('gift_items.*')
->where($campaign_foreignK = '{id}')
->get()
);
return view('DBqueries.boxView', $data);
}
My question is, how can I specifically return data, that only belongs to that specific box, since I am not able to use mysql where option.
For reference, these are the database tables:
Basically, I would need to match my URL's id with campaign_foreignK
Thank you in advance.
First of all, yout need to start to use Laravel Eloquent Models.
But doing by your way (the hardest):
You need to create a route in web or api, something like that:
Route::get('/box/{id}', [BoxController::class, 'view']);
Then you need to put this function on your controller:
function view($id){
/**
* You can do it by 2 ways:
* 1 - Do a where in the result of DB query (the bad way)
*/
$list = DB::table('campaigns_gifts')
->join('gift_items', 'gift_items.id', '=', 'campaigns_gifts.gift_foreignK')
->select('gift_items.*')
->where($campaign_foreignK = '{id}')
->get();
$list = (array)collect($list)->where('abc', 123);
/**
* Or the second way (the best is to use the Eloquent, but using DB the following is the best)
* 1 - Get the relations:
* Is git_items id the key for gift_foreignK ? i'm supposing that is it! so....
*/
$giftsIds = array_values((array)DB::select("select * from campaigns_gifts where campaign_foreignK = $id"));
$giftsIdsString = implode($giftsIds, ',');
$list = (array)DB::select("select * from gift_items where id in ($giftsIdsString)");
return view('DBqueries.boxView', ['list' => $list]);
}

How to get all atrribute labels in yii 1

I have Brand table(it contains brand_id, brand_name, b_year ) and this code
`Products::model()->getAttributeLabel('brand_id')`
var_dump(Products::model()->getAttributeLabel('brand_id'));
It shows only brand_id label. How can I show all labels instead of one?
Try this
var_dump(Products::model()->attributeLabels());
Hii attributeLabels() is a function in Model. It return a array with database field as key.
to get all labels you have to just call it with no agruments like
var_dump(Products::model()->attributeLabels()); // this will return complete array
Where as getAttributeLabel is written in CActiveRecord and it expect and argument by definition it will not given all fields lablels
Please try this,
$lables = Products::model()->attributeLabels();
print_r($labels);
$lables returns all labels from Products model.

Laravel - How to query if an array field in DB contains a value

I have a field in my model Person called jobs that I'm casting as an array. jobs is an array of ids related to a Jobs table. I want to be able to query Person and return all that have a certain id in their jobs array. I see that Laravel has a whereIn clause which checks if a database value is in an array but I need the opposite - to check whether a database array contains a value.
Am I stuck having to use where('jobs', 'like', '%"' . $job_id . '"%')?
I'm not sure there's an opposite however if you're simply looking to make the query a bit more reusable, you could make it a local scope by adding this to your Person model:
/**
* Scope a query to only include persons with given job id.
*
* #return \Illuminate\Database\Eloquent\Builder
*/
public function scopeHasJob($query, $jobId)
{
return $query->where('jobs', 'like', "%\"{$jobId}\"%");
}
The name of the scope hasJob may interfere with the parent QueryBuilder method has so you might have to come up with a different name for it.
Now you can use Person::hasJob($job->id). However rather than storing the job ids in a column as an array, you should consider creating a pivot table to map the relationships between a person and job. You can do this using php artisan:
php artisan generate:pivot persons jobs
php artisan migrate
Then you need to add the relationship into your Person model:
/**
* The person's jobs
*/
public function jobs()
{
return $this->belongsToMany('App\Job');
}
So you can query your Person model by Job like this:
Person::whereHas('jobs', function ($query) {
return $query->whereId($job->id);
});
Laravel includes whereJsonContains(): So your field jobs that you
are casting as an array, that can query as :
->whereJsonContains('jobs', 3)
That way worked for me ...
I am adding a little more info to Zubayer Hossain's answer
The data types have to match:
// [1, 2]
->whereJsonContains('players', 1) // Works.
->whereJsonContains('players', '1') // Doesn't work.
// ["1", "2"]
->whereJsonContains('players', '1') // Works.
->whereJsonContains('players', 1) // Doesn't work.
whereJsonContains can be used in cases where we need to check if a value matches a json encoded field in our table.
Courtesy : https://newbedev.com/php-wherejsoncontains-and-with-laravel-example
You could use something like this query.
$k = ["359045532","359079612","359079372","359081292","359081052","359086332","359086092","359111892","359111652"];
Modal::whereIn('myitems', $k)->get();
<!-- If you have a collection of value like this: -->
$category_id = 1,2,3,...;
$category_id = $_POST['category_id'];
$myArray = explode(',', $category_id);
<!-- If you already have array data you can pass this to the following query -->
$data = DB::table('tablename')->select('*') ->whereIn('catcode', $myArray)->get();

Symfony2 - Doctrine query

I have problem with Doctrine query in my Symfony2 project.
That my code:
public function getLender($lender) {
$lender = str_replace("_", " ", $lender);
$this->qb->select('ld, ld.entry, ll.name, ll.logo')
->from('PageMainBundle:LoanDescription', 'ld')
->leftJoin(
'PageMainBundle:loanLender',
'll',
\Doctrine\ORM\Query\Expr\Join::WITH,
'ld.lender = ll.lenderId'
)
->where('ll.name=?1')
->setParameter(1, $lender);
return $this->qb->getQuery()->getResult();
}
When in select section i choose columns it works very well - returns values of columns. unforunelly when I try something like that:
$this->qb->select('ld')
I don't get pure values but sometkhing strange.
How can I get values of all db columns?
This "strange" thing is most probably an LoanDescription collection of object (entity) instances. So to get value of entry field you need to call $entity->getEntry() on this entity object (assuming that you have such method defined in your entity)
OR
You can use getArrayResult instead of getResult and you should get array with valies

How to check if data is already in database using PHP?

Situation:
My PHP script will run once a way.
and that will store data in my database.
Since 1 week is good enough for me, so I only want to keep just that.
Let's say if today is Friday OR 5 (in my case).
Is there a way to check if date == 5 is already exist in the database, and possibly override it with the one ?
If today is Friday/5, then all the old data with date == 5 should be overridden and store the new one instead.
Literally, I only want to store one full week worth of data.
Tomorrow, and the next will repeat the same logic.
Here is how I insert my data into my database :
$data = new Data;
$data->name = $name;
$data->description = $description;
$data->dayOfWeek = $today; // could be 0,1,2,3,4,5,6
$data->save();
I am not sure, how do I accomplish that in Laravel.
Any tip/suggestion will be much appreciated !
Why don't you do this outside of your foreach loop - before you insert
Data::where("dayOfWeek","=", $today )->delete();
That should take care of what you want, then you can continue insert just like normal:
$data = new Data;
$data->name = $name;
$data->description = $description;
$data->dayOfWeek = $today; // could be 0,1,2,3,4,5,6
$data->save();
You can use INSERT ... ON DUPLICATE KEY UPDATE eg. like that
INSERT INTO `data` (`name`, `description`, `day`) VALUES (:name, :description, :day)
ON DUPLICATE KEY UPDATE name = VALUES(name), description = VALUES(description)
Of course you have to declare unique key on day field to make it work.
If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an UPDATE of the old row is performed. For example, if column a is declared as UNIQUE and contains the value 1, the following two statements have identical effect:
Sample Code:
INSERT INTO table (a,b,c) VALUES (4,5,6)
ON DUPLICATE KEY UPDATE c=9;
Firstly get the data from the database;
$data = Data::where('dayOfWeek', $today)->first();
Then check to see if the data is there, if it is update if not create.
if (!is_null($data)){
$data->update($new_attribute_data)
}
else {
Data::create($new_attribute_data);
}
As a note: Using the update method can require you to fill the $fillable array within your model if you putting GET or POST data into it. You can do it like so;
class Data extends Eloquent {
...
protected $fillable = ['name','description','dayOfWeek'];
}
And Laravel will fill the Model Attribute with the corresponding data within the Input.
EDIT:
As a faster way for the above method, use the updateOrCreate method;
Data::updateOrCreate(['dayOfWeek' => $today], $new_attribute_data);
This will search for Data models with attributes that match the first parameters, and will update its other attributes with the second parameter. Ref

Categories