associated not save data in second table in cakephp 3.4 - cakephp-3.0

In my case three table just like facilities, ports and port_facilities. first two table make relation in port_facilities table and relation is many to many.
I already insert data facilities table and after this i try to insert data in port table and port_facilities. In port table data insert successfully but in port_facilities data not insert i try with associated but i dont know why data not insert in second table.
In port_facilities two primary key is 'port_id', 'facility_type_id'
port_id related to port and facility_type_id related to facilities table
In port Table my relation is
$this->hasMany('PortFacilities', [
'foreignKey' => 'port_id',
]);
In my controller add function data format is
$data = [
'port_name' => 'First Post',
'city' => 'First Post',
'state' => 'First Post',
'zipcode' => 'First Post',
'country_id' => 1,
'phone' => 'First Post',
'remark' => 'First Post',
'status' => 1,
'PortFacilities' => [
['port_id' => 81,
'facility_type_id' => 2,
'free' => 1,
'facility_cost' => 25,
]
]
];
$port = $this->Ports->newEntity();
$port = $this->Ports->patchEntity($port, $data,['associated' => ['PortFacilities']]);
$this->Ports->save($port);
In ports table data successfully insert but in PortFacilities not.
Please can you explain me about this where i m messing some or wrong code.
Thanks

Related

Aloglia records are updating with wrong datatypes

I am facing some issues in algolia records. There are some attributes in me People table (e.g. id(int), user_id(int), name(varchar) ... etc).
When I add new records through Laravel 5.5 to database then everything works fine at algolia but I try to update record then although records are updating perfectly but the datatypes are changing. Like before Updating record user_id is int = 6 after updating the name or something else the user_id is converting to varchar implicitly.
I dont know whats happening.
before updating this record:
After updating the same record:
The insertion code is:
$new_person = People::create([
'user_id' => Auth::user()->id,
'stage_id' => 0,
'source_id' => 0,
'agent_id' => 0,
'custom_field_id' => 0,
'fname' => $request->first_name,
'lname' => $request->last_name,
'phone' => $request->phone,
'email' => $request->email,
'avatar' => "/images/user.png",
'name_slug' => createPeopleSlug($request->first_name , $request->last_name)
]);
The code for update is:
$person = People::find($request->personID);
$person->tags = $tagsString;
$person->save();
I am not expert of Aloglia
This issue will be resolved by adding Laravel casts variable to your Model, simple.
protected $casts = [
'user_id' => 'integer',
'agent_id' => 'integer',
'company_person_id' => 'integer',
];
Cheers!

Update Rows, column values represent as keys

Here's the overview of my table.
The thing is, the value of meta_key column represent as keys.
The problem is, how would I update the fields with user_id. For example, I want to update gender, employee_type, division, mobile that has a different values each field that has a user_id of 1.
I really have no idea how though, but on Eloquent there's this ->insert() to insert multiple values.
$meta_values = [
['user_id' => $user->id, 'meta_key' => 'mobile', 'meta_value' => $mobile,],
['user_id' => $user->id, 'meta_key' => 'address', 'meta_value' => $address,],
['user_id' => $user->id, 'meta_key' => 'gender', 'meta_value' => $gender],
['user_id' => $user->id, 'meta_key' => 'birthday', 'meta_value' => Carbon::parse($birthday)->format('Y-m-d')],
['user_id' => $user->id, 'meta_key' => 'employee_type', 'meta_value' => $employee_type],
['user_id' => $user->id, 'meta_key' => 'division', 'meta_value' => $division],
['user_id' => $user->id, 'meta_key' => 'date_employed', 'meta_value' => Carbon::parse($date_employed)->format('Y-m-d')],
['user_id' => $user->id, 'meta_key' => 'avatar', 'meta_value' => $images->avatar]
];
$user->userMeta()->insert($meta_values);
Here's the insert version, but how's the update version going to be or what it looks like. Any ideas?
I think it would be possible by using loop, but I probably think that it would not be a great idea.
--- EDITED ---
For now, here's my temporary solution. Here's what I'm gonna do in the first place but, until someone has an answer to this problem, this is my solution for now.
//List all fields in an array to be updated
$meta_array = ['mobile', 'address', 'gender', 'birthday', 'employee_type', 'division', 'date_employed'];
for ($i = 0; $i < count($meta_array); $i++) {
$user->userMeta()
->where('meta_key', $meta_array[$i])
->update(['meta_value' => ${$meta_array[$i]}]);
}
Something along this lines should work for you:
$meta_array = array('gender', 'employee_type', 'division', 'mobile');
Your\Model::where('user_id', 1)
->whereIn('meta_key', $meta_array)
->update(['meta_value' => 'some_new_value']);
The above PHP code should correspond to the following raw SQL query which you gave in your question as an example:
UPDATE your_table
SET meta_value='some_new_value'
WHERE user_id=1 AND meta_key IN ('gender', 'employee_type', 'division', 'mobile')

BEGIN,INSERT,COMMIT with ON DUPLICATE KEY UPDATE

I have two tables:
1- beoordelingen
2 - sterren
I need to update 3 values in table beoordelingen and insert new values into table sterren
How do I do that?
ON DUPLICATE KEY doesn't work and I can't find anywhere how to do it.
$sql=$dbo->prepare("BEGIN;INSERT INTO beoordelingen(beoordelingid,userid,werkid,inlijn,
sjabloon,conclusie,save)
VALUES ('$beoordelingid','$user','$werkid','$inlijn','$sjabloon','$conclusie','0')
ON DUPLICATE KEY UPDATE
beoordelingid=VALUES(beoordelingid),userid=VALUES(userid), werkid=VALUES(werkid),
inlijn=VALUES(inlijn),sjabloon=VALUES(sjabloon),conclusie=VALUES(conclusie),
save=VALUES(save);
INSERT INTO sterren (beoordelingid,userid,werkid,titelwerk,actie,sterren)
VALUES ('$beoordelingid','$user','$id','$titelwerk',
'$actie','$sterren'); COMMIT");
I adapted the following. The insert1 still won't work. Insert2 works
$dbo->beginTransaction();
//NOT WORKING
$insert1 = $dbo->prepare("INSERT INTO beoordelingen(beoordelingid, userid, werkid, inlijn, sjabloon, conclusie, save)
VALUES (:beoordelingid, :user, :werkid, :inlijn, :sjabloon, :conclusie, '0')
ON DUPLICATE KEY UPDATE
beoordelingid=VALUES(beoordelingid),
userid=VALUES(userid),
werkid=VALUES(werkid),
inlijn=VALUES(inlijn),
sjabloon=VALUES(sjabloon),
conclusie=VALUES(conclusie),
save=VALUES(save);"
);
//THIS WORKS
$insert2 = $dbo->prepare("INSERT INTO sterren (beoordelingid, userid, werkid, titelwerk, actie, sterren)
VALUES (:beoordelingid, :user, :id, :titelwerk, :actie, :sterren);"
);
//NOT WORKING
$insert1->execute(array(
'beoordelingid' => $beoordelingid,
'user' => $user,
'werkid' => $werkid,
'inlijn' => $inlijn,
'sjabloon' => $sjabloon,
'conclusie' => $conclusie,
'save' => $save
));
//THIS WORKS
$insert2->execute(array(
'beoordelingid' => $beoordelingid,
'user' => $user,
'id' => $werkid,
'titelwerk' => $titelwerk,
'actie' => $actie,
'sterren' => $sterren
));
$dbo->commit();
My last problem:
$sterren=$_POST['sterren'];
$user=$_REQUEST['user'];
$userid=$_POST['userid'];
$actie=$_POST['actie'];
$dbo->beginTransaction();
//THIS WORKS
$insert1 = $dbo->prepare("INSERT INTO sterren(sterren,userid,actie)
VALUES (:sterren, :userid, :actie);"
);
//THIS DOESN"T WORK
$insert2 = $dbo->prepare("INSERT INTO sterren(sterren,userid,actie)
VALUES (:-sterren, :user, :actie);"
);
//THIS WORKS
$insert1->execute(array(
'sterren' => $sterren,
'userid' => $userid,
'actie' => $actie
));
//THIS DOESN"T WORK
$insert2->execute(array(
'-sterren' => $sterren,
'user' => $user,
'actie' => $actie
));
$dbo->commit();
This is not how to use prepared statements (->prepare()) or how to use a transaction with PDO.
First off, prepare() is for "preparing" one SQL query with placeholders so that you can pass the parameters in a later function (execute()) and avoid SQL injection from concatenating strings.
Second, if you want to use a transaction then you should use PDO's beginTransaction and commit functions.
Try something like this:
$dbo->beginTransaction();
$insert1 = $dbo->prepare('INSERT INTO beoordelingen(beoordelingid, userid, werkid, inlijn, sjabloon, conclusie, save)
VALUES (:beoordelingid, :user, :werkid, :inlijn, :sjabloon, :conclusie, :save)
ON DUPLICATE KEY UPDATE
beoordelingid=VALUES(beoordelingid),
userid=VALUES(userid),
werkid=VALUES(werkid),
inlijn=VALUES(inlijn),
sjabloon=VALUES(sjabloon),
conclusie=VALUES(conclusie),
save=VALUES(save);'
);
$insert2 = $dbo->prepare('INSERT INTO sterren (beoordelingid, userid, werkid, titelwerk, actie, sterren)
VALUES (:beoordelingid, :user, :id, :titelwerk, :actie, :sterren);'
);
$insert1->execute(array(
'beoordelingid' => $beoordelingid,
'user' => $user,
'werkid' => $werkid,
'inlijn' => $inlijn,
'sjabloon' => $sjabloon,
'conclusie' => $conclusie
));
$insert2->execute(array(
'beoordelingid' => $beoordelingid,
'user' => $user,
'id' => $id,
'titelwerk' => $titelwerk,
'actie' => $actie,
'sterren' => $sterren
));
$dbh->commit();

CakePHP model associations - Random order on retrieve of associated model for HABTM

I am retrieving data:
$mydata = $this->ProductList->find('all', array('order' => 'rand()', 'conditions' => array('name' => 'we love')));
I have set up a HABTM relationship to the Product model. As you can see, I am fetching all products in the 'we love'-list. Now, I want those Products I am retrieving to be randomised. But they are not, instead the MySQL is randomised on the ProductList model as you can see in the SQL. Why is that? How can I get the random fetch on the Products instead?
Resulting MySQL query:
SELECT `ProductList`.`id`, `ProductList`.`name` FROM `database`.`product_lists` AS `ProductList` WHERE `name` = 'we love' ORDER BY rand() ASC
SELECT `Product`.`id`, `Product`.`category_id`, `Product`.`name`, `Product`.`price`, `Product`.`description`, `ProductListsProduct`.`product_list_id`, `ProductListsProduct`.`product_id` FROM `database`.`products` AS `Product` JOIN `database`.`product_lists_products` AS `ProductListsProduct` ON (`ProductListsProduct`.`product_list_id` = 3 AND `ProductListsProduct`.`product_id` = `Product`.`id`)
EDIT:
There are so many different ways to approach this; to get a random product from a user's product list. You could do it with PHP - just find all of the products and then use rand() to pick on from the returned array. You could set a Model query condition. The list goes on...
I would probably create an alias to the Product model in ProductList called RandomProduct. You could set the query for the retrieved product when you set the relationship:
public $hasMany = array(
'RandomProduct' => array(
'className' => 'Product',
'foreignKey' => 'product_list_id',
'order' => 'Rand()',
'limit' => '1',
'dependent' => true
)
);
You can then use the containable behavior so that this model is only retrieved when you need it. (You wouldn't need to do this if recursive finds are greater than -1, but I usually do that as best practice so that my models only query for the data that they need.) The following would return any ProductList called 'we love' and a "random" product associated with that list.
$mydata = $this->ProductList->find(
'all',
array(
'conditions' => array(
'name' => 'we love'
)
),
'contain' => array(
'RandomProduct'
)
);

How to search value from serialized data n mysql?

I want to search data which is stored in serialized form in this table.
Table Structure
For
meta_key - mgm_member_options
meta_value -
a:31:{s:2:"id";s:1:"1";s:13:"custom_fields";a:6:{s:10:"first_name";s:5:"Admin";s:9:"last_name";s:5:"Basil";s:7:"address";s:0:"";s:4:"city";s:0:"";s:5:"state";s:0:"";s:3:"zip";s:0:"";}s:22:"other_membership_types";a:0:{}s:12:"payment_info";a:0:{}s:6:"coupon";a:0:{}s:7:"upgrade";a:0:{}s:6:"extend";a:0:{}s:4:"code";s:10:"mgm_member";s:4:"name";s:10:"Member Lib";s:11:"description";s:10:"Member Lib";s:7:"setting";a:0:{}s:6:"saving";s:1:"1";s:8:"trial_on";s:1:"0";s:10:"trial_cost";s:1:"0";s:14:"trial_duration";s:1:"0";s:19:"trial_duration_type";s:1:"d";s:16:"trial_num_cycles";s:1:"0";s:8:"duration";s:1:"0";s:13:"duration_type";s:1:"m";s:6:"amount";s:1:"0";s:8:"currency";s:3:"USD";s:9:"join_date";s:0:"";s:13:"last_pay_date";s:0:"";s:11:"expire_date";s:0:"";s:15:"membership_type";s:5:"guest";s:6:"status";s:8:"Inactive";s:12:"payment_type";s:0:"";s:13:"autoresponder";s:0:"";s:10:"subscribed";s:0:"";s:9:"rss_token";s:32:"af8214c978dedcaa066bd8c223b7d22d";s:13:"user_password";s:16:"m9ROVxRwfxWwJzti";}
I want to find zip code.
How can do this using sql query?
Query that i am using
if(isset($_GET['as_zip']) && !empty($_GET['as_zip'])){
$as_zip = $_GET['as_zip'];
array_push($meta_query_array, array('key' => 'mgm_member_options', 'value' => $as_zip, 'compare' => '='));
} // prepare arguments $args = array( 'role' => $role, 'number' => '10', 'orderby' => 'display_name', 'fields' =>
'all_with_meta', 'meta_query' => $meta_query_array );