I want to insert registration data, I followed the existing tutorial, but got an error exception.
$users = new UsersModel();
$data = [
'name' => $this->request->getPost('name'),
'email' => $this->request->getPost('email'),
'password' => password_hash($this->request->getPost('password'), PASSWORD_DEFAULT)
];
$users->insert($data);
My Model:
<?php
namespace App\Models;
use CodeIgniter\Model;
class UsersModel extends Model
{
protected $table = "users";
protected $primarykey = "id";
protected $returnType = "object";
protected $useTimestamps = true;
protected $allowedFields = ['name', 'email', 'password'];
}
throw the exception:
mysqli_sql_exception #1054
Unknown column 'updated_at' in 'field list'
The exception is
mysqli_sql_exception #1054
Unknown column 'updated_at' in 'field list'
Which strongly suggests that it is expecting a column called updated_at.
You have set protected $useTimestamps = true;
So as per the documentation:
$useTimestamps
This boolean value determines whether the current date is
automatically added to all inserts and updates. If true, will set the
current time in the format specified by $dateFormat. This requires
that the table have columns named ‘created_at’ and ‘updated_at’ in the
appropriate data type.
So you need to create the columns created_at and updated_at
Related
I need to declare properties inside an Active Record model. I want to use PHP 8 syntax. So I did:
final class Post extends ActiveRecord
{
public ?int $id = null;
public ?int $user_id = 0;
public string $slug;
public ?string $title = null;
public ?string $content = null;
public ?string $created_at = null;
public ?string $updated_at = null;
public ?string $published_at = null;
public static function tableName(): string
{
return 'posts';
}
public function rules(): array
{
return [
[['user_id', 'title', 'content'], 'required'],
[['user_id'], 'integer'],
[['content'], 'string'],
[['slug', 'created_at', 'updated_at', 'published_at'], 'safe'],
[['title'], 'string', 'max' => 512],
];
}
}
But now all the fields become inaccessible. When I remove them as class fields, everything is ok.
As we can see Yii just removes these model attributes since I declared them as class properties:
SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a
default value The SQL being executed was: INSERT INTO posts (id)
VALUES (DEFAULT)
In most active record models in yii2 you put comments to get IDE-support like autocompletion since yii2 is using magic methods to resolve the fields to columns.
See Yii2 BaseActiveRecord all the columns are stored in a field _attributes.
So i think the best way you could do is add the doc comments as the following example to your ActiveRecord classes:
/**
* #property ?int id
* #property string slug
* #property-read Author[] authors
*/
note the #property-read indicates a relation and there is a subtile difference when accessing $object->authors; vs $object->getAuthors();. In the first case the relation query is executed and the results are returned as array (via magic methods) and in the second case you get back the raw query that is not executed yet.
And to keep with the authors example the relation method would look like the following:
public function getAuthors(): ActiveQuery
{
return $this
->hasMany(Author::class, ['id' => 'author_id'])
->viaTable('post_author', [ 'post_id' => 'id' ]);
}
I am having a table name Student ( id , name , division ). To store data into this table I am sending json string as a request to the api in laravel.
Request json string is,
{
"name":"abc",
"division":"a",
"city":"xyz"
}
Controller Code
public function registerStudent(Request $request){
$requestData = $request->json()->all();
$studentModel = Student::create($requestData);
}
Student Model
class Student extends Model
{
protected $fillable = [
'id', 'name','division'
];
}
When i execute this code , i get the following error,
Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'city' in 'field list' (SQL: insert into `Student`...
now my question here is, in what way I can store the data into database from json request with having extra keys into json object/array.
You could use the collections only method.
public function registerStudent(Request $request){
$requestData = collect($request->json()->all())->only(['name', 'division']);
$studentModel = Student::create($requestData);
}
I use three tables playlists, entityAssets, and playlistEntityAssets.
PlaylistEntityassets table has 2 columns playlist_id, asset_id referring to the other two tables. when I try to get data filter by playlist_id it gives me this error.
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'playlist_entity_assets.play_list_id' in 'where clause' (SQL: select * from playlist_entity_assets where playlist_entity_assets.play_list_id = 3 and playlist_entity_assets.play_list_id is not null)
this is my get method. even though my table has a "playlist_id" column. this query calls for the "play_list_id" column.
public function show($subdomain, $id) {
$universe = Auth::user()->getCurrentUniverse();
$playlist = PlayList::find($id);
//return empty responce
if( $playlist == null){
return Response::json();
}
$playlistAssets = array();
$playlistEntityAssets = $playlist->playlistEntityAssets;
foreach($playlistEntityAssets as $plEntityAsset){
$asset = $plEntityAsset->entityAsset;
$plAsset = ['asset' => $asset ];
$playlistAssets[] = $plAsset;
}
return Response::json($playlistAssets);
}
I want to fitler all enityAssets data filter by playlist_id in the "playlistEntityAssets" table.
use Illuminate\Database\Eloquent\Model;
class PlaylistEntityAssets extends Model
{
protected $table = 'playlist_entity_assets';
public function user()
{
return $this->belongsTo('asset');
}
public function universe()
{
return $this->belongsTo('Universe');
}
public function playlist(){
return $this->belongsTo('Playlist', 'playlist_id');
}
public function entityAsset(){
return $this->belongsTo('EntityAsset', 'asset_id');
}
I already fixed the problem. The answer is to put the exact column name in the playlist model.
class PlayList extends Eloquent{
public function playlistEntityAssets()
{
return $this->hasMany('PlaylistEntityAssets', 'playlist_id' );
}
}
I am using SQL SERVER 2014 and Laravel 5.4 I habe a tble named tblMyUser whose primary key MyUserId
Now I want to insert one row in table and get Last Insered Id but this return wrong id with respect to sql server tblMyUser table
This is my Model MyUser.php
namespace App;
use DB;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class MyUser extends Authenticatable
{
use Notifiable;
protected $table = 'tblMyUser';
protected $primaryKey = 'MyUserId';
protected $fillable = ['Name','DOB','CustUserId','CreatedBy','UpdatedBy'];
public $timestamps = false;
public static function addUser($params){
$myUser = MyUser::create(array(
'Name' => $params['Name'],
'DOB' => $params['DOB'],
'CustUserId' => $params['CustUserId'],
'CreatedBy' => $params['CreatedBy'],
'UpdatedBy' => $params['UpdatedBy']
));
echo "<pre>";print_r($myUser->MyUserId);exit;
// Its returning wrong Id which is not in tblMyUser
}
}
In laravel 5.4 you can get it by 2 way
By using insertGetId method. link
$lastID = DB::table('table_name')->insertGetId(['field_name'=>$field_vale]);
echo $lastID;
By using getPdo() method.
$lastID = DB::getPdo()->lastInsertId();
echo $lastID;
I have two tables that are related directly in a one-to-one relationship. One is the standard Yii2 user table (abbreviated field list here for clarity) and the other is the employee table that contains user_id. How can I create a globally accessible variable (and the actual code to access the employee id) that I can use anywhere in my application that will give me the logged in user's employee id and how would I call that variable? I wish I could say that I've tried a few things, but unfortunately I am relatively new to Yii2 and have no idea where to start with global variables like this. Thanks for any help.
user table:
id
username
password
etc
employee table:
id
user_id (related in a one-to-one relationship to the user table)
The Employee Model:
<?php
namespace frontend\models\base;
use Yii;
/**
* This is the base model class for table "employee".
*
* #property integer $id
* #property integer $user_id
*
* #property \common\models\User $user
*/
class Employee extends \yii\db\ActiveRecord
{
public function rules()
{
return [
[['user_id', 'required'],
[['user_id'], 'integer'],
[['user_id'], 'unique']
];
}
public static function tableName()
{
return 'employee';
}
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'user_id' => Yii::t('app', 'User ID'),
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getUser()
{
return $this->hasOne(\common\models\User::className(), ['id' => 'user_id']);
}
}
A very simple way is the use of $param array
You can initially config the default value in
your_App\config\param.php
and accessing using
\Yii::$app->params['your_param_key']
Looking to your Employee model (for me ) you don't need a global var you could simply use the getUser
$myUser = Employee::user();
but you need the param you can assign using
\Yii::$app->params['my_user'] = Employee::user();
or in user
\Yii::$app->params['my_user'] = Yii::$app->user->id
or for retrive the model related to actual user from table
$myEmpModel = Employee::find()->where['user_id' => Yii::$app->user->id]->one();
I believe proper way is to use relations in your User model. First method is proper relation with activerecord, second one will get id using relation defined above it. so You will add these methods in your User model:
/**
* #return \yii\db\ActiveQuery
*/
public function getEmployee()
{
return $this->hasOne(Employee::className(), ['user_id' => 'id']);
}
public function getEmployeeId()
{
return $this->employee ? $this->employee->id : NULL; // set to NULL or anything you expect to be if record is not found
}
Then you can call it like this from everywhere in your app:
$employee_id = Yii::$app->user->identity->employeeid;
This will only work for User model because it implements Identity, otherwise you would need to instantiate model class first, lets say like this:
$user_id = 5; // 5 is id of user record in DB
$user = User::findOne($user_id);
$employee_id = $user->employeeid;
// or using first of 2 relations ...
$employee_id = $user->employee->id;