Laravel insert data to one to one relation table - laravel

How can I insert data (that linking each other) to the table 'PEMBATALAN' that has one to one relation (have foreign key in both table) to the other table 'PERMINTAAN'.
here is the 'pembatalan' model code:
class Pembatalan extends Model
{
public $table = "PEMBATALAN";
public $primaryKey = "ID_PEMBATALAN";
public $fillable = array(
'PERMINTAAN_ID',
'ALASAN_PEMBATALAN',
'TGL_PEMBATALAN',
'FILE_PEMBATALAN',
'STATUS_PEMBATALAN',
);
public function permintaan() {
return $this->belongsTo('Permintaan', 'PERMINTAAN_ID', 'ID_PERMINTAAN');
}
}
'Permintaan' model code:
class Permintaan extends Model
{
public $table = "PERMINTAAN";
public $fillable = array(
'NOMOR_TICKET',
'TGL_PERMINTAAN',
'NAMA_REQUESTER',
'PEMBATALAN_ID',
);
public $primaryKey = "ID_PERMINTAAN";
public function tikpro() {
return $this->belongsToMany('Tikpro','TIKPRO_ID','ID_TIKPRO');
}
public function pembatalan() {
return $this->hasOne('Pembatalan','PEMBATALAN_ID','ID_PEMBATALAN');
}
}
Thanks in advance

Create your Permintaan and then use that reference to create the relation
Only Pembatalan needs a foreign key of Permintaan or the other way around.
$p = Permintaan::create([
'NOMOR_TICKET' =>$value,
'TGL_PERMINTAAN' =>$value,
'NAMA_REQUESTER' =>$value,
]);
$p->pembatalan()->create([
'ALASAN_PEMBATALAN' =>$value,
'TGL_PEMBATALAN' =>$value,
'FILE_PEMBATALAN' =>$value,
'STATUS_PEMBATALAN' =>$value,
]);
Laravel docs has a very good explanation on one to one relationships using hasOne and belongs to

Related

Model relationship creation uses the wrong field in Laravel

I want to create a new model using the relationship between a two model module and chapter and they have HasMany relationship between them as follow :
//Module mode
public function chapters()
{
return $this->hasMany(Chapter::class, 'module_slug', 'slug');
}
//Chapters Model
public function module()
{
return $this->belongsTo(Module::class, 'module_slug', 'slug');
}
And here's how I'm storing the models :
$module = Module::create([
'title' => $request->module_title,
'icon' => $request->module_title
]);
$module->chapters()->create([
'pdf_url' => $path,
'title' => $request->chapter_title
]);
The Issue :
The problem I got is that the $module->chapters()->create() is using the id not the slug which I'm specifying as the primary key like this :
//Module model
protected $primaryKey = 'slug';
protected $keyType = 'string';
//Chapters model
protected $primaryKey = 'slug';
protected $keyType = 'string';
I don't know why it uses the id field like this screenshot :
Add this to your models:
public $incrementing = false;

laravel eloquent doesn't use protected table name

In my model i added protected $table, but when i'm going to use it laravel does't use it. This is my role models:
class Role extends Model
{
protected $table = 'role';
protected $primaryKey = 'ROLE_ID';
protected $casts = [
'ACTIVE' => 'boolean',
];
protected $fillable = [
'ROLE', 'ACTIVE', 'TYPE'
];
public $timestamps = false;
public function groups()
{
return $this->belongsToMany(Group::class, GroupRole::class, 'ROLE_ID', 'GROUP_ID');
}
}
And this is Group model:
class Group extends Model
{
protected $table = 'groups';
protected $primaryKey = 'GROUP_ID';
protected $fillable = [
'GROUP_ID', 'GROUP_NAME', 'PARENT_GROUP', 'ACTIVE'
];
protected $casts = [
'ACTIVE' => 'boolean',
];
public $timestamps = false;
public function type()
{
return $this->belongsTo(GroupType::class, 'TYPE', 'TYPE_ID');
}
public function roles()
{
return $this->belongsToMany(Role::class, GroupRole::class, 'GROUP_ID', 'ROLE_ID');
}
}
And this is group_role table model. It handles many to many relation between role and group:
class GroupRole extends Model
{
protected $table = 'group_role';
protected $primaryKey = 'GROUP_ROLE_ID';
protected $fillable = [
'COMMENT', 'ROLE_ID', 'GROUP_ID'
];
public $timestamps = false;
}
Problem begin when i want to use this models. For example:
$role = App\Role::first();
$groups = $role->groups;
Laravel returns this error messages:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'favian_mydb.App\GroupRole' doesn't exist (SQL: select groups.*, App\GroupRole.ROLE_ID as pivot_ROLE_ID, App\GroupRole.GROUP_ID as pivot_GROUP_ID from groups inner join App\GroupRole on groups.GROUP_ID = App\GroupRole.GROUP_ID where App\GroupRole.ROLE_ID = 1)
I tried to replace App\GroupRole with group_role and executing in mysql. It works fine. Am i missing something?
The Problem is in your roles relation:
public function roles()
{
return $this->belongsToMany(Role::class, GroupRole::class,'GROUP_ID','ROLE_ID');
}
The belongsToMany expects the intermediate table name as second argument, not the class name.
So you have to define it like this:
public function roles()
{
return $this->belongsToMany(Role::class, 'group_role','GROUP_ID','ROLE_ID');
}
I think the problem is in you relation functions. Try to use strings instead of Model::class.
Example:
return $this->return $this->belongsTo('App\GroupType', 'TYPE', 'TYPE_ID');
Hope this works.

Using properly of eager loading

I have two tables: contracts and contractitems. I want to display all my Contract items and have a search for searching the contractor name.
Contracts
id
contract_code
contractor_name
ContractItems
id
contracts_id
item_name
class ContractItems extends Eloquent {
protected $table = 'ContractItems';
protected $guarded = [ 'id' ];
public $timestamps = false;
public function contract()
{
return $this->hasOne('Contracts', 'id', 'contracts_id');
}
}
$x = ContractItems::with(array('contract' => function($query){
$query->where('contractor_name', 'LIKE' , '%name%');
}))->take(1)->get();
I tried the code above but it is not displaying the correct data.

laravel one to Many Relationship with multiple table, query not optimized?

I have a table call table1(i am using some pretended name for tables here) like follow
id_table1 description
And Model is Like
`
class Table1 extends \Eloquent {
public $timestamps = false;
protected $table = 'table1';
protected $fillable = [ 'description'];
protected $primaryKey = 'id_table1';
public function relation5s(){
return $this->hasMany('Relation5','id_table1','id_table1');
}
public function relation4s(){
return $this->hasMany('Relation4','id_table1','id_table1');
}
public function relation3s(){
return $this->hasMany('Relation3','id_table1','id_table1');
}
public function relation2s(){
return $this->hasMany('Relation2','id_table1','id_table1');
}
public function relation1s(){
return $this->hasMany('Relation1','id_table1','id_table1');
}
}
This table is related to 5 tables names relation_table1,relation_table2 ... and so on.
Here is a sample model code for relation tables
<?php
use Illuminate\Database\Eloquent\Relations;
class Relation1 extends \Eloquent {
public $timestamps = false;
protected $table = 'relation_table1';
protected $fillable = [ 'id_table1','idReseller', 'login', 'password', 'type','etc'];
public function childs(){
return $this->hasMany('Relation2','id_relation','id');
}
public function table1(){
return $this->belongsTo('Table1','id_table1','id_table1');
}
public function scopeActive($query){
return $query->whereRaw('type % 2 = 1');
}
public function scopeInactive($query){
return $query->whereRaw('type % 2 = 0');
}
}
`
Problem is when i query below
$level=1; // i am controlling 5 relation tables in same controller via $level from route
$class = "Relation".$level;
$collection = new $class;
$results = $collection->with('Table1')->orderBy($sort,$order)->paginate();
its working showing all result from relation table .. but its doesn't solve n+1 query problem. i mean for every row from relation1 its querying each time on table1 .. any idea how i can solve this ?
thanks in advance
You code is correct, just replace "Table1" by "table1":
$results = $collection->with('table1')->orderBy($sort,$order)->paginate();
Take a look at Eager loading, you are using it with the with method so it will load them in the first query
$level=5
$class = "Relation".$level::with('Table1')->orderBy($sort,$order)->paginate();

Populate laravel object with relationships

I want to populate Every CustomerEvent with the Customer related to the CustomerEvent.
When I Loop through the object and call to $customerevent->customer foreach object I can get the customer related to that event but Can I populate the all objects in the main object without looping through every single event ?
I want to do something like this:
$typeOne = CustomerEvent::typeOne()->get();
$customersWithTypeOne = $typeOne->Customers;
Here my code:
Table 1: "events"
id, customer_id
Model for Table 1 "CustomerEvent":
<?php
class CustomerEvent extends Eloquent{
protected $guarded = ['id'];
public $table = "event";
protected $softDelete = true;
public function scopeTypeOne($query)
{
$followUps = $query->where('type_id', '=', '1');
}
public function Customers()
{
return $this->belongsTo('Customer', 'customer_id');
}
}
Table 2: "customers"
id
Model for Table 2 "Customers":
<?php class Customer extends BaseModel{
protected $guarded = ['id'];
}
EventController:
public function index()
{
$typeOne = CustomerEvent::typeOne()->get();
$customersWithTypeOne = $typeOne->Customers;
dd($customersWithTypeOne);
}
From you database scheme I see customer has many events, so I would recommend to define this relationship in you Customer model.
class Customer extends BaseModel{
protected $guarded = ['id'];
public function events()
{
return $this->hasMany('CustomerEvent', 'customer_id');
}
}
Then you will be able to query customers with events:
$customersWithTypeOne = Customer::whereHas('events', function($query){
$query->where('type_id', 1);
})->get()
Maybe Ardent can help you: https://github.com/laravelbook/ardent
It's an extension for Eloquent models and very popular.

Resources