Inserting operation is:
$r = [
'idVisitor' => 4,
'lastname' => 'fg',
'firstname' => '11',
'document_number' => '444',
'idEvent' => 2
];
$g = Visitor::insert($r);
Model is:
class Visitor extends Model
{
public $timestamps = false;
protected $table = 'visitors';
protected $fillable = ['firstname', 'lastname', 'middlename', 'document_number', 'pincode', 'ckecked', 'date_cheked', 'user_cheked', 'company', 'code', 'status', 'idEvent', 'date', 'birthday'];
protected $primaryKey = 'idVisitor';
}
if to do this:
$g = Visitor::insert($r);
var_dump($g);
It gives me true, so Laravel considers that it was committed.
Dump SQL is:
CREATE TABLE `visitors` (
`idVisitor` int(11) NOT NULL,
`firstname` varchar(45) NOT NULL,
`lastname` varchar(45) NOT NULL,
`middlename` varchar(45) DEFAULT NULL,
`document_number` varchar(45) NOT NULL,
`pincode` varchar(10) DEFAULT NULL,
`ckecked` int(11) DEFAULT '0',
`date_cheked` date DEFAULT NULL,
`user_cheked` int(11) DEFAULT NULL,
`company` varchar(100) DEFAULT NULL,
`code` varchar(100) DEFAULT NULL,
`idEvent` int(11) NOT NULL,
`status` int(11) NOT NULL DEFAULT '1',
`date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`birthday` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `visitors`
--
ALTER TABLE `visitors`
ADD PRIMARY KEY (`idVisitor`,`idEvent`),
ADD UNIQUE KEY `document_number_UNIQUE` (`document_number`),
ADD UNIQUE KEY `pincode_UNIQUE` (`pincode`),
ADD UNIQUE KEY `code_UNIQUE` (`code`),
ADD KEY `fk_visitors_users1_idx` (`user_cheked`),
ADD KEY `fk_visitors_events1_idx` (`idEvent`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `visitors`
--
ALTER TABLE `visitors`
MODIFY `idVisitor` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=18;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `visitors`
--
ALTER TABLE `visitors`
ADD CONSTRAINT `fk_visitors_events1` FOREIGN KEY (`idEvent`) REFERENCES `events` (`idEvent`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_visitors_users1` FOREIGN KEY (`user_cheked`) REFERENCES `users` (`idUser`) ON DELETE NO ACTION ON UPDATE NO ACTION;
COMMIT;
I use MySQL 5.0.12
Also I tried:
$g = new Visitor();
$g->lastname = 4;
$g->middlename = 4;
$g->document_number = 444;
$g->firstname = 4;
$g->idEvent = 2;
$g->save();
please use
$g = new Visitor();
$g->idVisitor = 4;
$g->firstname= 4;
$g->idVisitor = 4
$g->save();
this is another way
$g = new Visitor(); call class without '()', so $g = new Visitor;
Related
I have created three tables users, courses and user_courses as shown below
CREATE TABLE `users` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`address` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`status` enum('0','1') COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
CREATE TABLE `courses` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`title` text,
`description` text,
`price` varchar(255) DEFAULT NULL,
`schedule` varchar(255) DEFAULT NULL,
`duration` varchar(255) DEFAULT NULL,
`summary` text,
`skills` text,
`mode` enum('0','1') DEFAULT NULL COMMENT '0-Online 1 -Instructor',
`random_token` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1
CREATE TABLE `user_courses` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) DEFAULT NULL,
`course_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1
Now with these tables, I want to bind relationship such as when I fetch Users I'm able to get courses for a user and when I get to courses I want users associated with the course.
Please help how I can achieve it.
I have got my answer so posting it here if it can help anyone.
The main thing here is to assign a many-to-many relationship. In my user model I have defined
public function courses()
{
return $this->belongsToMany('App\Course');
}
In course model
public function users()
{
return $this->belongsToMany('App\User');
}
Actually, it depends on how you want to use the relationship.In some parts of the code you will need $user->courses or more likely to query $course->users or both.
Now here user_course table will be assumed as a pivot table. So in model, you can write it as
public function courses()
{
return $this->belongsToMany('App\Course', 'user_courses');
}
Here you can also specify the actual names of the fields of that particular pivot table i.e user_courses table.Then, what all we have to do is just add two more parameters first is the current model field and then add the field of the model being joined like
public function courses()
{
return $this->belongsToMany('App\Course', 'user_courses','user_id', 'course_id');
}
So using the above model relationship you can easily fetch users with all the respective courses by
User::->with('courses')->get();
First Fix
First, fix the user_course table structure the users table has id as integer while it's being referenced in user_course in user_id as bigint.
Solution
The first thing to do is to create models in the application. Then create relationships within models and finally use those relationships.
Create models
By using command line
php artisan make:model Course
php artisan make:model UserCourse
You can create them manually if you like. By default, they will be created in app folder with namespace App. For example, the user model will be App/User and so on.
The user model will already exists as its shipped with laravel default installation.
Create relationships
In user model add the following function
public function courses()
{
$this->belongsToMany(Course::class, 'user_course');
}
You can leave the Course Model empty if you are not planning to make a reverese relation from course to user. The one above defines relation from user to courses
Usage
Say in a controller you can use this as
public function someFunctionInController()
{
$usersWithCourses = \App\User::with('courses')->get()->toArray();
//result of a single user record will look something like this
/**
[
'id' => 1,
'name' => 'some name'
... //other users table columns
//the courses will be an array of array content and will be automatically injected
'courses' => [[
'id' => 1 //the course id
... //course table columns,
'pivot' => [
'user_id' => 1,
'course_id' => 1
]
],[
'id' => 3 //the course id
... //course table columns,
'pivot' => [
'user_id' => 1,
'course_id' => 3
]
]]
]
**/
}
I have a People table
CREATE TABLE `people` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`job_title` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`profile_pic` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`departments` varchar(500) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=95 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
An a departments table
CREATE TABLE `departments` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`people_id` int(11) NOT NULL,
`department_id` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=50 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
One person can be in many departments
In the departments table the foreign_key is people_id
In my people model
public function departments()
{
return $this->hasMany('App\Models\Departments', 'id', 'people_id');
}
and finally I try and return some results
return $people::find(1)->departments;
I get the error,
**ErrorException in web.php line 129:
Trying to get property of non-object**
Forgive me if this is a stupid error, I have used laravel for a while but never set up models with relationships before.
Try this Piece of code:-
Get All records
$people = People::with('departments')->get();
$people = json_decode(json_encode($people),true) //Convert in to array
echo "<pre>"; print_r($people); die; //print it
Get 1 record
$people = People::with('departments')->first();
$people = json_decode(json_encode($people),true) //Convert in to array
echo "<pre>"; print_r($people); die; //print it
Hope it helps!
So in the end it was a stupid issue.
$people::find(1)->departments;
Find takes an id but the id of 1 did not exist.
I'm getting an error when saving some empty text, textarea fields. Laravel forms this sql query:
SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '' for column 'inside_area' at row 1 (SQL: insert into `ads` (`street`, `quarter`, `building_number`, `inside_area`, `price`, `admin_comment`, `valid_to`, `price_heating`, `rooms`, `floor_number`, `floors_number`, `kitchen_area`, `years`, `public_comment`, `video_url`, `3d_url`, `user_id`, `updated_at`, `created_at`) values (, , , , , , , , , , , , , , , , 1, 2017-03-13 14:33:50, 2017-03-13 14:33:50))
P.S. db table was created not in laravel way - I'm using existing tables, this may be important.
UPDATED: problem are only with INT fields, if they has empty form field on saving!
Table:
CREATE TABLE `ads` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`ad_type_id` int(11) DEFAULT NULL,
`city_id` int(11) DEFAULT NULL,
`street` varchar(255) DEFAULT NULL,
`quarter` varchar(255) DEFAULT NULL,
`building_number` varchar(255) DEFAULT NULL,
`inside_area` int(11) DEFAULT NULL,
`price` int(11) DEFAULT NULL,
`show_price_per_meter` int(1) DEFAULT NULL,
`price_heating` int(10) DEFAULT NULL,
`admin_comment` text,
`valid_to` datetime DEFAULT NULL,
`rooms` int(11) DEFAULT NULL,
`floor_number` int(11) DEFAULT NULL,
`floors_number` int(11) DEFAULT NULL,
`kitchen_area` int(11) DEFAULT NULL,
`balcony` int(1) DEFAULT NULL,
`balcony_glazed` int(1) DEFAULT NULL,
`years` int(11) DEFAULT NULL,
`dyn_house_type_id` int(11) DEFAULT NULL,
`dyn_heating_id` int(11) DEFAULT NULL,
`dyn_installation_ids` int(11) DEFAULT NULL,
`public_comment` text,
`video_url` varchar(11) DEFAULT NULL,
`3d_url` varchar(11) DEFAULT NULL,
`available_for_trade` int(1) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
FORM:
{!! Form::open(['url'=>'ads']) !!}
{!! Form::number('inside_area', null, ['class'=>'form-control']) !!}
{!! Form::close() !!}
Route:
Route::resource('ads', 'AdsController');
Save action:
public function store() {
$input = Request::all();
\App\Ad::create($input);
return redirect('/ads/my_index');
}
P.S.2 If I provide any value to inside_area field, it goes ok and the next error is for price field.
You can use attribute mutator for each integer attribute. In these mutators you can prepare data before inserting into DB.
In your case you should create mutators in your model Ads for every field with the type INT:
// define a mutator for the field "inside_area"
public function setInsideAreaAttribute($value)
{
$this->attributes['inside_area'] = (int) $value;
}
I understand that creating such a mutator for each INT field is boring, but it will also grant you ability to control user input before inserting into DB.
You can find more information about mutators here (for the latest version of Laravel at this moment):
Laravel 5.4, Defining a Mutator:
https://laravel.com/docs/5.4/eloquent-mutators#defining-a-mutator
Perhaps, you are passing string data to 'inside_area' variable. Because there is more default null fields at your table, like 'city_id', 'ad_type_id'
another way is to use Iatstuti and provide in Ad.php model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Iatstuti\Database\Support\NullableFields;
class Ad extends Model {
use NullableFields;
public $timestamps = true;
protected $nullable = [
'inside_area'
];
protected $fillable = [
'user_id',
'ad_type_id',
'inside_area'
];
}
trying to get TraineeID where $arrTID not in tbl_attendance_processed but my code below return all TraineeID from tbl_attendance_processed.
If I use where_in then the query return absolute result those TraineeID are really matched. Just not returning appropriate when I use where_not_in.
Model:
public function getNotMatch_TID($arrTID,$atnDate){
$this->db->select('TraineeID');
$this->db->where_not_in('TraineeID', $arrTID);
$this->db->where('attnDate', $atnDate);
$query = $this->db->get('tbl_attendance_processed');
return $query->result();
}
controller:
$arrTID = $this->input->post('Present');
$atnDate = $this->input->post('attnDate');
$nonMatch= $this->AttendanceModel->getNotMatch_TID($arrTID,$atnDate);
print_r($nonMatch);
echo last query:
table schema:
CREATE TABLE `tbl_attendance_processed` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`TraineeID` varchar(7) CHARACTER SET utf8 NOT NULL,
`attnDate` date NOT NULL,
`inTime` time NOT NULL,
`outTime` time NOT NULL,
`Status` varchar(10) NOT NULL,
`ClassCount` tinyint(1) NOT NULL DEFAULT '1',
`Reason` varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=3186 DEFAULT CHARSET=latin1
I have 2 tables: production and *production_summary*. production store data about each production that is produced, sold or discarded. *production_summary* store daily summary about production. This is the relevant DB structure:
CREATE TABLE `production` (
`id` int(10) unsigned NOT NULL auto_increment,
`created` date NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `production_summary` (
`id` int(10) unsigned NOT NULL auto_increment,
`date` date NOT NULL,
`summary` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Models are generated by Gii and names respectively are: Production and ProductionSummary.
I defined relation like this:
class Production extends CActiveRecord
{
...
public function relations()
{
return array(
'summary' => array(self::HAS_ONE, 'ProductionSummary', '', 'on' => 'summary.date = t.created' ),
);
}
...
}
It's working fine when I get model:
$model = Production::model()->with( 'summary' )->findByPk($id);
But lazy loading fail with: unknown column t.created. And I get it: Yii doesn't join tables while lazy loading, just querying the ProductionSummary table.
Using with() is not a problem in my case, but start to wonder what is the right way of defining this type of relations?
As of Yii 1.1.9 you can define relations this way:
return array(
'summary' => array(self::HAS_ONE, 'ProductionSummary', array('date' => 'created')),
);