I have an 'Edit page' with a form, where I want to update some data.
My Models:
Actividad.php:
public function materials()
{
return $this->belongsToMany('Material', 'actividad_material')->withTimestamps();
}
And Material.php:
public function actividads()
{
return $this->belongsToMany('Actividad', 'actividad_material')->withTimestamps();
}
My code (Controller):
public function update($id)
{
$input = array_except(Input::all(), '_method');
$v = Validator::make($input, Actividad::$rules);
// return 'Hala';
if($v->passes())
{
$actividad = Actividad::find($id);
$material_id = Input::get('material_id');
$actividad->materials()->sync($material_id);
Actividad::find($id)->update($input);
// return 'hola';
return Redirect::route('actividads.index');
}
return Redirect::back()->withErrors($v);
}
The application gives me an error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'material_id' in 'field list' (SQL: update actividads set updated_at = 2014-07-20 16:20:03, material_id = 1 where id = 16)
I suppose it is because it's looking for a column in my 'actividads' that doesn't already exist! Maybe I have to change $input = array_except(Input::all(), '_method');... I think I'm telling with that, that every inputs in the form are in my 'Actividad', and this is not true. I need to update my pivot table with 'material_id'.
Thank you very much in advance!
Related
I want to delete data through the api but it is showing an error because it is necessary to delete records in the properties table.
SQLSTATE[23000]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server] The DELETE statement conflicted with the REFERENCE constraint "FK_Interests_Properties_User". The conflict occurred in database "CADASTRO", table "dbo.Interests_Properties", column 'interests_user_id'. (SQL: delete from [Interests_User] where [user_id] = 1515626)
I created the model that performs actions on the Interests_Properts table, but when I try to delete the data that has the same interests_user_id, errors are occurring.
InterestsUser.php:
use App\Source\InterestsProperties;
class InterestsUser extends Model
{
protected $connection = 'sql_cadastro';
protected $table = 'Interests_User';
protected $primaryKey = 'id';
public $timestamps = false;
public function properties()
{
$this->belongsToMany(InterestsProperties::class, 'foreign_key');
}
public static function lgpdInterestsUser($id_user, $action)
{
if ($action == 'search') {
$data = InterestsUser::where('user_id', $id_user)->get();
if (count($data) > 0) {
return $data;
} else {
return false;
}
} elseif ($action == 'delete') {
$data = InterestsUser::with('properties')->where('user_id', $id_user)->get();
foreach ($data->properties as $p) $p->delete();
if ($data > 0) {
return 'Success Remove.';
} else {
return 'Not Found.';
}
} else {
return "Action Incorrect!";
}
}
}
InterestsProperties.php
class InterestsProperties extends Model
{
protected $table = 'Interests_Properties';
protected $primaryKey = 'id';
public $timestamps = false;
}
The error is occurring when trying to remove with cascade:
Call to undefined method Illuminate\Database\Eloquent\Builder::foreign()
Table Structure
Interests_User
id
interest_id
user_id
created_at
updated_at
Interests_Properties
id
interests_user_id
key
value
created_at
updated_at
At DB level, using onDelete: when migrating your InterestsProperties model you'll have a line like
$table->foreignId('foreign_key')
to that add ->onDelete('cascade')
after that update each time you delete a record from the main table it will do it in this one to.
At PHP level,
$data = InterestsUser::with('properties')->where('user_id', $id_user)->first();
foreach($data->properties as $p) $p->delete();
PD: Those will remove the property record too.
I'm new to CakePHP. I have a table to keep record of user's activity by creating a log in it. The table has two columns
+----+------------+-----------+
| id | user_id | comment |
+----+------------+-----------+
I want to pass values from within controller like
$this->ActivityLogs->log($user_id, 'Message sent');
log is a custom function inside ActivityLogs model which will record some more data along with passed data
public function log($user_id = null, $message = null)
{
... record code goes here
return true;
}
But couldn't get how to write insert query inside model.
How can I create custom methods like this and also can anyone suggest me good resource to go through model queries and understanding.
public function log($user_id = null, $message = null){
//I assume here that your table name is 'logs'
$logsTable = \Cake\ORM\TableRegistry::get('Logs', array('table' => 'logs'));
$log = $logsTable->newEntity();
$log->user_id = $user_id;
$log->body = $message ;
if ($logsTable->save($log)) {
return true;
}
return false;
}
In a cakephp Model, I have this code:-
class ApplyRequest extends AppModel {
public $name = 'ApplyItem';
public function saveItemTrip($sender_id, $carrier_id, $item_id, $trip_id, $applied_by, $applied_to)
{
$queryInsert = "INSERT INTO apply_items (sender_id, carrier_id, item_id, trip_id, applied_by, applied_to)
VALUES ('$sender_id', '$carrier_id', '$item_id', '$trip_id', '$applied_by', '$applied_to')";
if($this->query($queryInsert))
return true;
else
return false;
}
}
Now, from the controller, I am calling the function:-
$isSuccess = $this->ApplyRequest->saveItemTrip($senderId, $memberId, $itemId, $getLastInsertID, $memberId, $senderId);
if($isSuccess)
{
$status = "1";
$message = "Trip-Request was successfull for this item";
}
else
{
$status = "3";
$message = "Error occured while applying for the item";
}
Now, the data is getting saved in the apply_items query. However, I am always getting the $status as 3.
it seems, $isSuccess is returned as false, for which I am getting status as 3.
What am I doing wrong?
Note
I have to write this query in such custom fashion. There is a whole lot of reason, which I can't explain here elaborately.
I think the problem is that you have to escape your variables in the insert statement.
$queryInsert = "INSERT INTO apply_items (sender_id, carrier_id, item_id, trip_id, applied_by, applied_to)
VALUES ('".$sender_id."', '".$carrier_id."', '".$item_id."', '".$trip_id."', '".$applied_by."', '".$applied_to."')";
i am submitting the location from textbox and putting values in comma seprated form like ngp,akola,kanpur.
Now i want if i have 3 values in location textbox then it insert 3 rows in location table one for ngp,second for akola and third for kanpur.
but it also takes last inserted id of user table and post all values in location table.
my location table have fields id,name,user_id.
in user_id column i need the last inserted id of user table and in name column i need to insert all values in table..
please help me to do this..below is my code.
function add() {
if (!empty($this->request->data)) {
$this->User->set($this->data['User']);
$isValidated = $this->User->validates();
if ($isValidated) {
// Generating UUID
if (!empty($this->request->data['User']['company_name'])) {
$this->request->data['User']['is_business'] = 1;
}
if ($this->User->save($this->request->data, array('validate' => false))) {
$lastId = $this->User->id;
$location = implode(',',$this->request->data['User']['location']);
for(i=1;i<=$location;i++){
$this->Location->save($location);
}
}
}
}
}
$lastId = $this->User->id;
$location = explode(',',$this->request->data['User']['location']);
foreach($location as $value){
$data = array();
$data["name"] = $value;
$data["user_id"] = $lastId;
$this->Location->save($data,false);
$this->Location->id = false;
}
Model::saveAll(array $data = null, array $options = array())
$this->request->data['Location'] = explode(',',$this->request->data['User']['location']);
if ($this->User->saveAll($this->request->data, array('validate' => false))){ // ...}
I need perform query "LOCK TABLE myTable WRITE"
<?php
$db = Database::instance();
$query = 'LOCK TABLE `myTable` WRITE';
$db->query(Database::WHAT_IS_THE_TYPE_SHOULD_SPECIFY_HERE_?, $query);
In framework Kohana 3.3
file ~/modules/database/classes/Kohana/Database.php
implements folowing types:
const SELECT = 1;
const INSERT = 2;
const UPDATE = 3;
const DELETE = 4;
but none of them fit in my case.
Any idea. Thanks.
Google works wonders. http://forum.kohanaframework.org/discussion/6401/lockunlock/p1
You can pass NULL as the first argument:
$db = Database::instance();
$query = 'LOCK TABLE `myTable` WRITE';
$db->query(NULL, $query);
From Kohana: http://kohanaframework.org/3.3/guide-api/Database_MySQL#query
if ($type === Database::SELECT)
{
// Return an iterator of results
return new Database_MySQL_Result($result, $sql, $as_object, $params);
}
elseif ($type === Database::INSERT)
{
// Return a list of insert id and rows created
return array(
mysql_insert_id($this->_connection),
mysql_affected_rows($this->_connection),
);
}
else
{
// Return the number of rows affected
return mysql_affected_rows($this->_connection);
}
As you can see that's why you're able to pass NULL.