I have three tables:
user
game
user_game
game.user_id - user which CREATE game. Table user_game describes users that ADDED games not create, it
has user_id and game_id fields. I have GameSearch Model which should search current user ADDED games. Here The search method;
public function search($params)
{
// HERE I SHOULD GET ONLY GAMES WHICH ADDED BY USER via table user_game
$query = Game::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => [
'defaultOrder' => [
'sorting' => SORT_DESC,
]
],
]);
if (!empty($params['pageSize'])) {
$dataProvider->pagination->pageSize = $params['pageSize'];
}
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'user_id' => $this->user_id,
'visible' => $this->visible,
'sorting' => $this->sorting,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
]);
$query->andFilterWhere(['like', 'name', $this->name])
->andFilterWhere(['like', 'slug', $this->slug])
->andFilterWhere(['like', 'image', $this->image])
->andFilterWhere(['like', 'description', $this->description])
->andFilterWhere(['>=', 'created_at', $this->date_from ? $this->date_from : null])
->andFilterWhere(['<=', 'created_at', $this->date_to ? $this->date_to : null])
->andFilterWhere(['>=', 'updated_at', $this->date_upd_from ? $this->date_upd_from : null])
->andFilterWhere(['<=', 'updated_at', $this->date_upd_to ? $this->date_upd_to : null]);
return $dataProvider;
}
So i need get games list via table user_game where user_id = current Id user, game_id = game id. Please help.
first of all you need two relation in first in Game model which will fetch one to many data from user_game table (model), then in model user_game you need write a relation to get user from user table (model)
$query->joinWith(['userGame', 'userGame.user']);
->andFilterWhere(['=', 'tbl_user.id', Yii::app()->user->id])
Related
log table with product id
product table
My Log tables contained data field having json data like
{"product-id":"14","product-name":"test","product-url":"\/projects\/test\/products\/lecture-details\/8","product-type":"lecture","product-price":"0"}
I want to join products table with the product id stored in data file.How can I do that?
log table "product-id": "14" this field need to be contained with product table.
$getQuery = $this->Log->find('all')->matching('Users', function ($q) { return $q->where(['Users.is_deleted' => 'n']);})->contain(['Users','Products'])->select(['user_id' => 'Users.id', 'username' => 'Users.username','fname' => 'Users.fname','lname' => 'Users.lname', 'email' => 'Users.email','view_date' => 'Log.dt_created_on','data' => 'Log.data'])->where($conditions);
Add this code Log association model
$this->hasOne('Products', [
'className' => 'Products',
'foreignKey' =>false,
'conditions' => array("Products.id=JSON_VALUE(cast(log.data as nvarchar(256)),'$.\"product-id\"')")
]);
I have a table called products. In product table I have 2 fields created_at and update_at. I don't want to change it to created and modified.
Without change table fields name, how can I assign that created_at field is created to get cakephp time helper auto update date ?
My entity I have tried below
protected $_accessible = [
'created_at' => $this->created,
'updated_at' => $this->modified,
];
Getting error.
Read the manual. https://book.cakephp.org/4/en/orm/behaviors/timestamp.html#basic-usage
If you need to modify fields with different names, or want to update additional timestamp fields on custom events you can use some additional configuration:
class OrdersTable extends Table
{
public function initialize(array $config): void
{
$this->addBehavior('Timestamp', [
'events' => [
'Model.beforeSave' => [
'created_at' => 'new',
'updated_at' => 'always',
],
'Orders.completed' => [
'completed_at' => 'always'
]
]
]);
}
}
I a struggling to save the chosen information from my selection box. I get the message:
"SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (clientpad_notes.notebooks, CONSTRAINT notebooks_contact_id_foreign FOREIGN KEY (contact_id) REFERENCES contacts (id) ON DELETE CASCADE) (SQL: insert into notebooks (name, contact_id, note_description, note_body, user_id, updated_at, created_at) values (assddsaasdadasasd, 3, saS, ssss, 2, 2018-03-03 19:18:51, 2018-03-03 19:18:51)
My problem is that I am bringing in information to notes create page from contacts table. So I have my tables linked with authentication with user_id and inside the notes tables I have contacts_id. I am aiming to select and save a contact name fetching it by it's id, when creating a new note. It is possible I have been going around doing this in a wrong way, I am a beginner at Laravel so any help would be appreciated.
Here is my notes controllers and create a note page.
NotesController.php
public function create()
{
$user_id = auth()->user()->id;
$user = User::find($user_id);
$contacts = Contact::find($user->contacts)->pluck('fullName');
return view('notebooks.create')->with('contacts', $contacts)->with('user', $user);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request,[
'name' => 'required',
'contact_id' => 'required',
'note_description' => 'required',
'note_body' => 'required',
]);
//Create a note
$notebook = new Notebook;
$notebook->name = $request->input('name');
$notebook->contact_id = $request->input('contact_id');
$notebook->note_description = $request->input('note_description');
$notebook->note_body = $request->input('note_body');
$notebook->user_id = auth()->user()->id; //currently logged in user show their notes
$notebook->save();
return redirect('/dashboard')->with('success', 'Your Note Was Created');
}
create.blade.php
<div class="col-6 col-sm-3">
{{Form::label('contact_id', 'Choose your Contact')}}
{{Form::select('contact_id', $user->contacts->pluck('fullName'), $contacts, ['class' => 'form-control'])}}
</div>
</div>
In the database which saved notes I have this:
Schema::create('notebooks', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->integer('contact_id')->unsigned()->nullable();
$table->foreign('contact_id')->references('id')->on('contacts')->onDelete('cascade');
$table->string('name');
$table->mediumText('note_description');
$table->mediumText('note_body');
$table->timestamps();
});
You made small mistake when working with Id's from other tables. You should check if the ID actually exists in the target table.
$this->validate($request,[
'name' => 'required',
'contact_id' => 'required|exists:contacts', //This will validate that the contact ID actually exists.
'note_description' => 'required',
'note_body' => 'required',
]);
//Create a note
$notebook = new Notebook;
$notebook->name = $request->input('name');
$notebook->contact_id = $request->input('contact_id');
$notebook->note_description = $request->input('note_description');
$notebook->note_body = $request->input('note_body');
$notebook->user_id = auth()->user()->id; //currently logged in user show their notes
$notebook->save();
Laravel validation#rule-exists
Update
$this->validate($request,[
'name' => 'required',
'contact_id' => 'required|exists:contacts,id', //check contacts table, for column ID
'note_description' => 'required',
'note_body' => 'required',
]);
SO after lots of searching I found a solution. In Create I had to use mapping:
public function create(Contact $contact)
{
$user_id = Auth::user()->id;
$user = User::find($user_id);
$contacts = $user->contacts->mapWithKeys(function($contact){
return [$contact->id => $contact->fullName];
});
// dd ($contacts);
return view('notebooks.create')->with('contacts', $contacts)->with('user', $user);
}
Then in Select I just called for this:
{{Form::label('contact_id', 'Choose your Contact')}}
{{Form::select('contact_id', $contacts, null, ['class' => 'form-control'])}}
Works like a charm, in case anyone else finds this useful
I am trying to give a condition in cakephp 3 get method, where data will fetch by foreign id not primary key. Here I have tried below code:
$eventPasswordAll = $this->EventPasswordAll->get($id, [
'conditions' => ['event_id'=>$id],
'contain' => ['Events']
]);
But it showing me data according to id(primary key), not by event_id. How I add this condition in get methods like where event_id=my get id ?
Don't use get, use find. According to CakePHP 3.0 Table API, the get method:
Returns a single record after finding it by its primary key, if no record is found this method throws an exception.
You need to use find:
$eventPasswordAll = $this->EventPasswordAll->find('all', [ // or 'first'
'conditions' => ['event_id' => $id],
'contain' => ['Events']
]);
// or
$eventPasswordAll = $this->EventPasswordAll->find()
->where(['event_id' => $id])
->contain(['Events']);
Sometimes you want to get the id and the userid..
$this->loadModel('Jobapplications');
$application = $this->Jobapplications->find('all', [
'conditions' => ['id' => $id, 'user_id' => $user_id]
]);
$application = $application->first();
I want to save a bunch of static records in my database with a given uuid, this is for testing purposes, so that on every system the application starts with the exact same dataset.
When inserting with SQL this is no problem but I wanted to use the CakePHP way ( I use a migrations file for this, but that does not matter).
The problem is that I give cake a data array like this and save it:
$data = [
['id' => '5cedf79a-e4b9-f235-3d4d-9fbeef41c7e8', 'name' => 'test'],
['id' => 'c2bf879c-072c-51a4-83d8-edbf2d97e07e', 'name' => 'test2']
];
$table = TableRegistry::get('My_Model');
$entities = $table->newEntities($data, [
'accessibleFields' => ['*' => true],
'validate' => false
]);
array_map([$table, 'save'], $entities );
Everything saves, but all my items have been given a different uuid, If I debug a record after saving it shows the original uuid in the entity
'new' => false,
'accessible' => [
'*' => true
],
'properties' => [
'id' => '6b4524a8-4698-4297-84e5-5160f42f663b',
'name' => 'test',
],
'dirty' => [],
'original' => [
'id' => '5cedf79a-e4b9-f235-3d4d-9fbeef41c7e8'
],
So why does cake generate a new uuid for me? and how do I prevent it
This doesn't work because primary keys are unconditionally being generated before the insert operation, see
https://github.com/cakephp/cakephp/blob/3.0.0/src/ORM/Table.php#L1486-L1490
// ...
$id = (array)$this->_newId($primary) + $keys;
$primary = array_combine($primary, $id);
$filteredKeys = array_filter($primary, 'strlen');
$data = $filteredKeys + $data;
// ...
$statement = $this->query()->insert(array_keys($data))
->values($data)
->execute();
// ...
Currently the UUID type is the only type that implements generating IDs, so providing custom IDs works with other types.
You can workaround this by for example overriding the _newId() method in your table so that it returns null, which effectively results in the existing primary key not being overwritten.
protected function _newId($primary)
{
// maybe add some conditional logic here
// in case you don't want to be required
// to always manually provide a primary
// key for your insert operations
return null;
}