Yii2 show item based on NOW() doesn't show the day itself - mysql

I'm trying to create a 'next in the agenda' item to place on an index page for an application I created with Yii2.
With the function below I retrieve the next item in the database that is 'upcoming' and shown based on the class of the trip and the date. I'm using the NOW() expression.
However, this means the next upcoming item will be shown until it hits the NOW() date, so its not shown anymore on the day itself. Ideally, i should have the upcoming item to show also until the time has passed the $this->time or only show the item after this one the day after NOW().
Anyone any tips how I can achieve this?
public function searchANext($params)
{
$query = Trip::find();
$time = new Expression('NOW()');
$query->where(['class' => Trip::CLASS_A])
->andWhere(['>=', 'date', $time])
->limit(1);
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => ['defaultOrder' => ['date' => SORT_ASC]],
'pagination' => false
]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
return $dataProvider;
}

I do not know why you are returning an ActiveDataProvider when you only want to get a single record, it is unnecessary for this case in my opinion.
Also, you are loading $params and validating the model after you create the query, so if the $params are not valid you will still get an error and you eventually return $dataProvider no matter what the load and validate methods return.
I suggest you make a few changes to your code:
public function searchANext($params)
{
// Try to load $params and validate the model first and return false
// instead of returning the result of the search.
if(!($this->load($params) && $this->validate())) {
return false;
}
// Let's get the currend DateTime. You might need to change this
// depending on the format of the 'date' field from 'Trip'
$now = date('Y-m-d H:i:s');
// Instead of creating an ActiveDataProvider, you can just get the one
// record directly and return it.
$model = Trip::find()
->where(['class' => Trip::CLASS_A])
->andWhere(['>=', 'date', $now])
->orderBy('date ASC')
->one();
return $model;
}

Related

How to combine four queries in laravel?

I have draws on my site, in order to take part in the draw, you need to do a certain action per day. And there is a code that checks it all:
$date = Carbon::today();
$sta = \DB::table('ets')->where('user_id', $this->user->id)->where('created_at', '>=', $date)->get();
$sta = \DB::table('ets_1x1')->where('user_id', $this->user->id)->where('created_at', '>=', $date)->get();
$sta = \DB::table('ets_low')->where('user_id', $this->user->id)->where('created_at', '>=',$date)->get();
$sta = \DB::table('ets_duel')->where('user_id', $this->user->id)->where('created_at', '>=', $date)->get();
if ($sta == NULL) {
return response()->json(['status' => 'error', 'msg' => 'Error']);
}
This code checks if there is a user record in 4 possible tables. I made an entry in the table ets_1x1, but still I can’t take part, because the error seemed to not find me in the database. I removed all the tables and left only ets_1x1 and I was accepted into the drawing.
As I understand it, the value is taken from the last request. How can I combine a query into 1 and do a check on these 4 tables?
UPD:
I also tried to give new names to the variables and display the response code differently, now participation in the drawing is accepted from all people, even from those who have not fulfilled the conditions, now it looks:
if(!empty($sta_1) || !empty($sta_2) || !empty($sta_3) || !empty($sta_4)) {
return response()->json(['status' => 'error', 'msg' => 'Error']);
}
Where my mistake?
That code is not going to work because:
The first piece of code will evaluate only the last request (and in consecuence, only if there is any existent user on the last table only).
The second piece of code is not being evaluated correctly, you are running empty function on a Laravel collection.
Why don't you try this? I think it should work:
$date = Carbon::now();
$userExists = false;
$tables = ['ets', 'ets_1x1', 'ets_low', 'ets_duel'];
foreach ($tables as $tableName) {
$result = \DB::table($tableName)
->where('user_id', $this->user->id)
->where('created_at', '>=', $date)
->get()
;
if ($result->isNotEmpty()) {
$userExists = true;
break;
}
}
if (!$userExists) {
return response()->json(['status' => 'error', 'msg' => 'Error']);
}

Yii2 SearchModel query - map integer values to strings

What I am trying to achieve:
I have a table with a type field which holds integer values. These integer values represent different strings.
I want to be able to search the table using the string values that the integers represent.
E.g type = abc rather than type = 0.
What have I tried:
I have created a query class for the model and tried to make use of the $boolean_map property:
class ReportQuery extends FilterableQuery
{
protected $filterable = [
'type' => 'LIKE',
'removed_the_rest'
];
protected $boolean_map = ["type" => [ 'addacs' => 0, "arudd" => 1,]];
}
Then I have overridden the find method of the model to use the query class:
public static function find()
{
$query = new ReportQuery(get_called_class());
return $query;
}
And in the search model I have:
public function search($params)
{
$query = Report::find();
$dataProvider = new ActiveDataProvider([
'query' => $query
]);
$this->load($params, '');
if (!$this->validate()) {
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'type' => $this->type,
]);
$query->andFilterWhere(['like', 'type', $this->type]);
return $dataProvider;
}
When searching by the string values I get an empty result. Searching by the integer values produces the data.
Any help is appreciated. Thanks.
Maybe it's better for you to make filter on that column instead of searching by string. You can do it for string as follows.
$filter = [
'example1' => 1,
'example2' => 2,
'example3' => 3,
];
$query->andFilterWhere(['like', 'type', $this->filter[$this->type]);
or in this place
// grid filtering conditions
$query->andFilterWhere([
'type' => $this->filter[$this->type],
])
also you can make filter dropdown on column, and for dropdown of that filter you can pass this array and just do
$query->andFilterWhere([
'type' => $this->type,
])
Why do you create mapping mechanism in query object? Okay, you show integer type as a string in frontend of your application, but the query shouldn't have details of representation. You should map string type to integer type in your search model. For example:
class ReportSearchModel extends ReportModel
{
public function mapType($value)
{
$items = [
'addacs' => 0,
'arudd' => 1
];
return array_key_exists($value, $items) ? $items[$value] : null;
}
public function search($params)
{
//another code
$query->andFilterWhere([
'type' => $this->mapType($this->type),
])
//another code
}
}
The alternative way is using an enum instead of mapping.

How to force data update on laravel validation custom unique

I'm new in laravel. I have a table with menu_id and title I tried to make this title field unique when have the same menu_id. I found the solution here
But I got problem when update it. Can anyone help please?
My code
Validator::extend('unique_custom', function ($attribute, $value, $parameters)
{
// Get the parameters passed to the rule
list($table, $field, $field2, $field2Value) = $parameters;
// Check the table and return true only if there are no entries matching
// both the first field name and the user input value as well as
// the second field name and the second field value
return \DB::table($table)->where($field, $value)->where($field2, $field2Value)->count() == 0;
});
public function updateSubmenu( Request $request) {
$this->validate( $request, [
'menu_id' => 'required',
'title' => 'required|unique_custom:posts,title,menu_id,'.$request->menu_id,
'order_by' => 'required|integer',
'description' => 'required'
],
[
'title.unique_custom' => 'This title already token'
]
);
}
Can you explain what problem have you got on update? Some exception?
Edit:
If you couldn't update record if title not changes, you need to add one condition to Validator:
Validator::extend('unique_custom', function ($attribute, $value, $parameters)
{
// Get the parameters passed to the rule
list($table, $field, $field2, $field2Value) = $parameters;
// If old value not changed, don't check its unique.
$current = \DB::table($table)->where('title')->first();
if( $current->{$field} == $value) {
return true;
}
return \DB::table($table)->where($field, $value)->where($field2, $field2Value)->count() == 0;
});

API Json in symfony form

i'm creating an application in symfony 2.8 (with php5.4) and in my form (that i'm building) i want to display a list of a projects through an API in json format.
Now i'm stuck, and i don't know how to do this.
I know the database of the API there is a table "projects" and i want target the column 'name' to display names of projects
here's my code:
/**
* #Route("/form")
*/
public function formAction(Request $request)
{
$url = 'https://website.com/projects.json';
$get_json = file_get_contents($url);
$json = json_decode($get_json);
$form = $this->createFormBuilder()
->add('Project', 'choice') // <-- ???
->add('send', 'submit' ,array('label' => 'Envoyer'))
->getForm();
$form->handleRequest($request);
return $this->render('StatBundle:Default:form.html.twig', array('form' => $form->createView(), 'project' => $json));
}
You can pass the choice as second argument as array as example:
$jsonAsArray = json_decode($get_json, true); // with true return an array
$builder->add('Project', 'choice', array(
'choices' => $jsonAsArray,
// *this line is important, depends of the data*
'choices_as_values' => false,
));
More info in the doc here.
Hope this help

QueryException - Integrity constraint violation: 1062 Duplicate entry when I hit the route 'logout'

I get the above error when I try and logout by hitting the route /logout. The table that is referenced in the screenshot is mdbids. It stores all of my IDs (strings, 16 characters in length).
When a user is created their MDBID (id) is stored in the mdbids table.
routes.php
<?php
Route::get('login', ['as' => 'login', 'uses' => 'SessionsController#create']);
Route::get('logout', ['as' => 'logout', 'uses' => 'SessionsController#destroy']);
SessionsController.php
<?php
use MDB\Forms\LoginForm;
class SessionsController extends \BaseController {
protected $loginForm;
function __construct(LoginForm $loginForm)
{
$this->loginForm = $loginForm;
}
public function create()
{
if(Auth::check()) return Redirect::to("/users");
return View::make('sessions.create');
}
public function store()
{
$this->loginForm->validate($input = Input::only('email','password'));
if (Auth::attempt($input)) {
Notification::success('You signed in successfully!');
return Redirect::intended('/');
}
Notification::error('The form contains some errors');
return Redirect::to('login')->withInput()->withFlashMessage("The form contains some errors");
}
public function destroy()
{
Auth::logout();
return Redirect::home();
}
}
The following is taken from my User.php (model) file. It isn't the whole file as it is fairly big, but this is the only part where IDs are mentioned.
User.php (model)
<?php
public function save(array $options = array())
{
$this->mdbid = $this->mdbid ?: str_random(16);
$this->key = $this->key ?: str_random(11);
Mdbid::create([
'mdbid' => $this->mdbid,
'table_number' => 7,
'table_name' => 'users',
'created_at' => Carbon::now(),
'updated_at' => Carbon::now()
]);
parent::save($options);
}
I don't know where to start to look. Any help is greatly appreciated.
Your issue is that the logout is actually causing save() to run, and therefor you are causing Mdbid::create to run with an already added key (presumably when you logged in, or somewhere else in your User model?).
Solution #1:
You could add a logout() function to the User model that you have. Something similar to
function logout()
{
$this->mdbid = null;
return Auth::logout()
}
This will stop two of the same keys being added to the logout function.
Solution #2
If what you are trying to accomplish is adding a row upon a successful login, then you should not be using the User::save() function, rather, you should be listening for the auth.login event.
Inside app/start/global.php, add the following code:
Event::listen('auth.login', function($user)
{
$user->mdbid = $user->mdbid ?: str_random(16);
$user->key = $user->key ?: str_random(11);
Mdbid::create([
'mdbid' => $user->mdbid,
'table_number' => 7,
'table_name' => 'users',
'created_at' => Carbon::now(),
'updated_at' => Carbon::now()
]);
});
This will ensure only one row gets added to Mdbid per successful login, instead of adding a new row (with the same id) each time the User model is updated.
Solution #3 (a.k.a. what was really wanted)
Each table has mdbid as a primary key. Each primary key needs to be added to the Mdbid table each time a new row is inserted.
The way that this should be done is with an Observer. The first part is adding a new Observer class that will be used for all of the models we want to add the mdbid into:
class MdbidObserver
{
/**
* Observe new rows being added into the database
*/
public function creating($model)
{
// note that $model could be any model
$model->mdbid = $model->mdbid ?: str_random(16);
$model->key = $model->key ?: str_random(11);
Mdbid::create([
'mdbid' => $model->mdbid,
'table_number' => 7,
'table_name' => 'users',
'created_at' => Carbon::now(),
'updated_at' => Carbon::now()
]);
}
}
The second part is adding the Observer to all the models that we want the mdbid added to (inside app/start/global.php):
User::observe(new MdbidObserver);
Artist::observe(new MdbidObserver);
Album::observe(new MdbidObserver);
To stop any issues with mdbid not actually being random already being used, you might want to add a loop just before $model->mdbid. Something similar to:
$isUnique = false;
while (!$isUnique)
{
$unqiueId = str_random(16);
$row = Mdbid::where('mdbid', $uniqueId);
if (is_object($row))
$isUnique = true;
}
$model->mdbid = $uniqueId;