Hi so I'm trying to save data through Cakephp3 framework. I have two tables Measures and MeasuresUsers. Measures has many MeasuresUsers
$data = [
'name' => $this->request->data['name'],
'description' => $this->request->data['description'],
'deleted' => $this->request->data['deleted'],
'chart_type' => $this->request->data['chart_type'],
'public' => $this->request->data['public'],
'user_id' => $this->request->data['user_id']
];
$measure = $this->Measures->newEntity($data,['associated' => ['MeasuresUsers']]);
$measure['measures_users'] = [
'user_id' => $user['id'],
'chart_type' => $this->request->data['chart_type'],
'deleted' => $this->request->data['deleted'],
'public' => $this->request->data['public']
];
$this->Measures->save($measure)
I'm able to save data into Measures table but not into the associative table (MeasuresUsers). I'm not sure what I'm missing here, any help or comments is appreciated!
#HarryM. is close, but you want to put your data into the $data array before creating the entity (the associated tag is kinda pointless if you're not providing that data!), and since it's a hasMany relation, I think you need to have the data in an array of arrays:
$data = [
'name' => $this->request->data['name'],
'description' => $this->request->data['description'],
'deleted' => $this->request->data['deleted'],
'chart_type' => $this->request->data['chart_type'],
'public' => $this->request->data['public'],
'user_id' => $this->request->data['user_id'],
'measures_users' => [
[
'user_id' => $user['id'], // Should this be $this->request->data['user_id'] instead?
'chart_type' => $this->request->data['chart_type'],
'deleted' => $this->request->data['deleted'],
'public' => $this->request->data['public'],
],
],
];
$measure = $this->Measures->newEntity($data, ['associated' => ['MeasuresUsers']]);
$this->Measures->save($measure);
Coming from CakePHP 2.x, I see your associate model is MeasuresUsers.
When you're setting the associated data in
$measure['measures_users'] = [
'user_id' => $user['id'],
'chart_type' => $this->request->data['chart_type'],
'deleted' => $this->request->data['deleted'],
'public' => $this->request->data['public']
];
Trying changing $measure['measures_users'] to $measure['MeasuresUsers']:
$measure['MeasuresUsers'] = [
'user_id' => $user['id'],
'chart_type' => $this->request->data['chart_type'],
'deleted' => $this->request->data['deleted'],
'public' => $this->request->data['public']
];
CakePHP's model conventions usually assume camel casing of what you have in the database e.g. DB Table it movie_tickets and Cake would expect is as MovieTicket unless otherwise declared in the Model itself.
Related
I need to create mongodb collection while executing code, by checking whether the collection is exists or not.
I tried below things
Yii::$app->db->createCommand()-> createCollection("collection_name");
but collection not created.
Please help.
Issue resolved..
Yii::$app->db->createCommand()->createCollection("collection_name")->execute();
and index will added for collection as,
$collectionName = Yii::$app->db->getCollection("collection_name");
$collectionName->createIndexes([
'key' => ['id' => 'int'],
'name' => 'id_index'
],
[
'key' => ['id' => 'int', 'category' => 'text'],
'name' => 'id_category_index',
]);
I created a new factory in Laravel called "CarFactory.php" and I want to use https://github.com/pelmered/fake-car.
This is the fake data that I will insert into my database using Tinker:
return [
'name' => $this->faker->vehicleBrand(),
'founded' => $this->faker->biasedNumberBetween(1998,2017, 'sqrt'),
'description' => $this->faker->paragraph()
];
In the Laravel usage code, I'm not sure where to put this (e.g. Car Model, CarFactory):
$faker->addProvider(new \Faker\Provider\Fakecar($faker));
$v = $faker->vehicleArray();
return [
'vehicle_type' => 'car',
'vin' => $faker->vin,
'registration_no' => $faker->vehicleRegistration,
'type' => $faker->vehicleType,
'fuel' => $faker->vehicleFuelType,
'brand' => $v['brand'],
'model' => $v['model'],
'year' => $faker->biasedNumberBetween(1998,2017, 'sqrt'),
];
Help is needed to know how to set this up.
in my app the user can update the info of stripe connected account, however I ONLY want to actullay update the value of the fields that appear in the request payload, I could do this with a simple if check but the way I update the stripe array method makes this issue more complicated .
Is there any syntax sugar or trick to make this easier.
How my update method looks;
public function editConnectedAccount(Request $request)
{
$account = Account::retrieve($request->connectedAccountId);
Account::update(
$request->connectedAccountId,
[
'type' => 'custom',
'country' => 'ES',
'email' => $request->userEmail,
'business_type' => 'individual',
'tos_acceptance' => [ 'date' => Carbon::now()->timestamp, 'ip' => '83.46.154.71' ],
'individual' =>
[
'dob' => [ 'day' => $request->userDOBday, 'month' => $request->userDOBmonth, 'year' => $request->userDOByear ],
'first_name' => $request->userName,
'email' => $request->userEmail,
'phone' => $request->userPhone,
'last_name' => $request->userSurname,
//'ssn_last_4' => 7871,
'address' => [ 'city' => $request->userBusinessCity, 'line1' => $request->userBusinessAddress, 'postal_code' => $request->userBusinessZipCode, 'state' => $request->userBusinessCity ]
],
'business_profile' =>
[
'mcc' => 5812, //got it
'description' => '',
//'url' => 'https://www.youtube.com/?hl=es&gl=ES', //got it
],
'capabilities' => [
'card_payments' => ['requested' => true],
'transfers' => ['requested' => true],
],
]
);
return response()->json([
'account' => $account,
], 200);
Consider using a Form Request where you preform validation. This will neaten up your controller for a start and also make validation (never trust user input!) reusable.
Assuming validation is successful, calling $request->validated() from inside your controller method will return only the fields present and validated. You can then use either fill($request->validated()) or update($request->validated()).
I am currently developing a skill for Amazon's echo dot which requires the use of persistent data. I ran into an issue when developing a web interface for my skill where I was not able to easily update the mapAttr column of the DynamoDB table used by the skill.
I've been trying to work this out for the last 2 days, I've looked everywhere including the documentation but can't seem to find anything that'll help me.
This is the code I am using:
$result = $client->updateItem([
'TableName' => 'rememberThisDBNemo',
'Key' => [
'userId' => [ 'S' => $_SESSION['userDataAsk'] ]
],
'ExpressionAttributeNames' => [
'#attr' => 'mapAttr.ReminderJSON'
],
'ExpressionAttributeValues' => [
':val1' => json_encode($value)
],
'UpdateExpression' => 'SET #attr = :val1'
]);
I have tried many different things so this might be just absolutely wrong, but nothing that I have found has worked.
The table has 2 columns, userId and mapAttr, userId is a string and mapAttr is a map. Originally I thought it was simply a JSON string but it was not like that as when I tried to update it with a JSON string directly it would stop working when read by Alexa.
I am only trying to update 1 out of the 2 attributes of mapAttr. That is ReminderJSON which is a string.
Any help would be appreciated. Thanks.
Try calling updateItem like this
$result = $client->updateItem([
'TableName' => 'rememberThisDBNemo',
'Key' => [
'userId' => [ 'S' => $_SESSION['userDataAsk'] ]
],
'ExpressionAttributeNames' => [
'#mapAttr' => 'mapAttr',
'#attr' => 'ReminderJSON'
],
'ExpressionAttributeValues' => [
':val1' => ['S' => json_encode($value)]
],
'UpdateExpression' => 'SET #mapAttr.#attr = :val1'
]);
However, please be aware that in order for this to work, attribute mapAttr must already exist. If it doesn't, you'll get ValidationException saying The document path provided in the update expression is invalid for update...
As a workaround, you may want to add a ConditionExpression => 'attribute_exists(mapAttr)' to your params, catch possible exception, and then perform another update adding a new attribute mapAttr:
try {
$result = $client->updateItem([
'TableName' => 'rememberThisDBNemo',
'Key' => [
'userId' => [ 'S' => $_SESSION['userDataAsk'] ]
],
'ExpressionAttributeNames' => [
'#mapAttr' => 'mapAttr'
'#attr' => 'ReminderJSON'
],
'ExpressionAttributeValues' => [
':val1' => ['S' => json_encode($value)]
],
'UpdateExpression' => 'SET #mapAttr.#attr = :val1'
'ConditionExpression' => 'attribute_exists(#mapAttr)'
]);
} catch (\Aws\Exception\AwsException $e) {
if ($e->getAwsErrorCode() == "ConditionalCheckFailedException") {
$result = $client->updateItem([
'TableName' => 'rememberThisDBNemo',
'Key' => [
'userId' => [ 'S' => $_SESSION['userDataAsk'] ]
],
'ExpressionAttributeNames' => [
'#mapAttr' => 'mapAttr'
],
'ExpressionAttributeValues' => [
':mapValue' => ['M' => ['ReminderJSON' => ['S' => json_encode($value)]]]
],
'UpdateExpression' => 'SET #mapAttr = :mapValue'
'ConditionExpression' => 'attribute_not_exists(#mapAttr)'
]);
}
}
A common task for me when I'm writing CakePHP applications is to type out an SQL file and write it into the database before running bake to generate some scaffolding. This is one of the very few gripes I have with CakePHP - doing this ties me into MySQL, and I'm wondering if there's a better way to do it through code. As an example, in some frameworks I can define the columns that my model uses along with the datatype and such, and then run a command through an admin interface to "build" the database based on what what's presented in the code. It will do this on whatever database is sitting behind the framework.
Is there a way for CakePHP 2.x can do something like this? I want to write out the database schema in my Model code and run a command like bake to automatically generate the tables and columns that I need. After diving into the cookbook docs, the _schema attribute seems to do what I want to do:
class Post{
public $_schema = array(
'title' => array('type'=>'text'),
'description' => array('type'=>'text'),
'author' => array('type'=>'text')
);
}
but there are no examples explaining what I would I do from there. Does the _schema attribute serve a different purpose? Any help would be appreciated!
not from your $_schema array itself. but creating and using a schema file schema.php in /APP/Config/Schema.
you can then run the bake command "cake schema create" which will then "Drop and create tables based on the schema file."
I might then look sth like this:
class YourSchema extends CakeSchema {
public $addresses = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 10, 'key' => 'primary'),
'contact_id' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => 10),
'type' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => 2),
'status' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => 2),
'email' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 50, 'collate' => 'utf8_unicode_ci', 'comment' => 'redundant', 'charset' => 'utf8'),
'created' => array('type' => 'datetime', 'null' => false, 'default' => NULL),
'modified' => array('type' => 'datetime', 'null' => false, 'default' => NULL),
'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)),
'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_unicode_ci', 'engine' => 'MyISAM')
)
// more tables...
}