Hi laravel is not inserting correct value in pivot table for many to many case.
Here my first model is
class ShippingAddress extends Eloquent {
protected $guarded = array('id');
protected $table = 'shippingAddress';
public function mwsOrder()
{
return $this->belongsToMany('MwsOrder',
'mwsOrders_shippingAddress',
'Address_id',
'AmazonOrderId'
);
}
}
Second Model is
class MwsOrder extends Eloquent {
protected $table = 'mwsOrders';
protected $primaryKey = 'AmazonOrderId';
public function shippAddress()
{
return $this->belongsToMany('ShippingAddress',
'mwsOrders_shippingAddress',
'AmazonOrderId',
'Address_id'
);
}
}
EER Diagram
Now when i run this
$mwsOrder = new MwsOrder;
$mwsOrder->AmazonOrderId = 'Eve 6';
$mwsOrder->save();
$address = new ShippingAddress;
$address->name = 'Naruto Uzumaki';
$address->save();
$address->mwsOrder()->attach($mwsOrder);
//$mwsOrder->shippAddress()->save($address);
laravel throws error and this is what laravel trying to run the query
(SQL: insert into mwsOrders_shippingAddress (Address_id,
AmazonOrderId) values (1, 3))
What i need is to generate this query
insert into mwsOrders_shippingAddress (Address_id,
AmazonOrderId) values (1, 'Eve 6')
Update:
Schema are:
Schema::create("shippingAddress", function(Blueprint $table)
{
$table->increments("id");
$table->string("Name");
$table->timestamps();
});
Schema::create("mwsOrders", function(Blueprint $table)
{
$table->increments("id");
$table->string("AmazonOrderId")->unique();
$table->timestamps();
});
Schema::create("mwsOrders_shippingAddress", function(Blueprint $table)
{
$table->increments("id");
$table->string("AmazonOrderId");
$table->foreign("AmazonOrderId")->references("AmazonOrderId")->on('mwsOrders');
$table->integer("shipping_address_id")->unsigned();
$table->foreign("shipping_address_id")->references('id')->on('shippingAddress');
$table->timestamps();
});
At first change the shippAddress to this:
// Specify the primary key because it's not conventional id
protected $primaryKey = 'AmazonOrderId';
public function shippAddress()
{
return $this->belongsToMany('ShippingAddress',
'mwsOrders_shippingAddress',
'AmazonOrderId',
'Address_id'
);
}
Then you may try this:
$mwsOrder = new MwsOrder;
$mwsOrder->AmazonOrderId = 'Eve 6';
$mwsOrder->save();
$address = new ShippingAddress(['name' => 'Naruto Uzumaki']);
$mwsOrder->shippAddress()->save($address); // Save and Attach
Related
I am getting the following error while trying to insert into the table users_basics
Illuminate\Database\Eloquent\Model::setAttribute(), 1 passed in
C:\xampp\htdocs\msadi\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasAttributes.php
on line 592 and exactly 2 expected
Here is my controller code:
public function create()
{
$userId = '10';
$userBasics = new UserBasics;
$userBasics->user_id = $userId;
$userBasics->save();
return redirect('users');
}
Here is my model:
class UserBasics extends Model
{
protected $table = 'users_basics';
protected $primaryKey = null;
protected $fillable = ['user_id'];
const UPDATED_AT = null;
const CREATED_AT = null;
}
Here is my user_basics migration:
public function up()
{
Schema::create('users_basics', function (Blueprint $table) {
$table->integer('user_id');
$table->bigInteger('adhaar_no')->nullable();
$table->string('mobile_no')->nullable();
$table->string('college_roll_no')->nullable();
$table->date('dob')->nullable();
$table->index('user_id');
});
}
I have tried adding UPDATED_AT, CREATED_AT and PrimaryKey to the table but none worked. The user_id is being inserted into the users_basics table but the error continues to show.
You should modify your model:
class UserBasics extends Model
{
protected $table = 'users_basics';
protected $primaryKey = null;
public $incrementing = false;
public $timestamps = false;
protected $fillable = ['user_id'];
}
because you not have field for Timestamp.
please add like this.
public function up()
{
Schema::create('sadi_users_basics', function (Blueprint $table) {
$table->integer('user_id');
$table->bigInteger('adhaar_no')->nullable();
$table->string('mobile_no')->nullable();
$table->string('college_roll_no')->nullable();
$table->date('dob')->nullable();
$table->timestamp(); <---- just insert this.
$table->index('user_id');
});
}
also, if you want to use softdelete then add $table->softDeletes();
it will make Deleted_at field in the table.
enjoy coding~!
I am making a one to many relationship, when I try to save it, it asks me to enter the FK should not I do it automatically?
class AlternativesCompetitorsImage extends Model
{
public function alternativecompetitors()
{
return $this->belongsTo(AlternativesCompetitor::class,'id');
}
}
class AlternativesCompetitor extends Model
{
public function alternativescompetitorsimages(){
return $this->hasMany(AlternativesCompetitorsImage::class,'alter_comp_id');
}
}
Controller
$ci = isset($id_image) ? $step->alternativescompetitorsimages : new AlternativesCompetitorsImage();
if( $request->hasFile('fileImg')){
$fileRequests = request()->file('fileImg');
$count = 0;
foreach ($fileRequests as $fileRequest) {
$keyCanvas = $c->key;
$stepKey = $stepType->key;
$public= public_path();
$directory =DIRECTORY_SEPARATOR."canvas".DIRECTORY_SEPARATOR.$keyCanvas.DIRECTORY_SEPARATOR.$stepKey;
$newName = "image".$count.".png";
Storage::deleteDirectory($directory);
$path = $fileRequest->storeAs("public".$directory,$newName);
$str = str_replace("\\", '/', $path);
$ci->url_img = $str;
!isset($id_image) ? $step->alternativescompetitorsimages()->save($ci) : $step->alternativescompetitorsimages()->update($ci->toArray());
DB::commit();
$count++;
}
Migrations
class CreateAlternativesCompetitorsImages extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('alternatives_competitors_images',function(Blueprint $table){
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('url_img',100);
$table->integer('alter_comp_id')->unsigned();
$table->timestamps();
$table->foreign('alter_comp_id')->references('id')->on('alternatives_competitors');
});
}
class CreateAlternativesCompetitors extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('alternatives_competitors',function(Blueprint $table){
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('step_id')->unsigned();
$table->string('valueA',10);
$table->string('valueB',10);
$table->timestamps();
$table->foreign('step_id')->references('id')->on('steps');
});
}
Next Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity
constraint violation: 1048 Column 'alter_comp_id' cannot be null (SQL:
insert into alternatives_competitors_images (url_img,
alter_comp_id, updated_at, created_at) values
(public/canvas/de939a01-1438-4aff-bb23-eb4f68653f5f/TEAM/image0.png, ,
2018-03-27 23:31:12, 2018-03-27 23:31:12)) in
C:\xampp\htdocs\canvas\vendor\laravel\framework\src\Illuminate\Database\Connection.php:647
You didn't stablish alter_comp_idto be nullable, and later you try to create a row with that column null. So... Either specify that value
$ci->alternativecompetitors()->associate($keyCanvas);
, or re-migrate the table to allow that field to be null, like this:
$table->integer('alter_comp_id')->unsigned()->nullable();
In my Model class;
Currently I have defined like;
return $this->belongsTo(related: Site::class,
foreignKey:'SiteId', ownerKey:'SiteId');; ----->This works.
But I want to define a combination as Foreign key,
eg: CompanyCode+SiteId
My Current and Target model has both columns(ie:CompanyCode+SiteId). That combination will return a single entry.I want to retrieve that in my current model.
How can I do that?
My Site Model is like;
class Site extends Model
{
protected $table = 'vwSitesPortal';
protected $primaryKey = 'SiteId';
...
My Current model is like;
class Alarm extends Model
{
protected $table = 'vwAlarm';
protected $primaryKey = 'AlarmId';
...
public function Site()
{
return $this->belongsTo(**related**: Site::class,
**foreignKey**:'SiteId', **ownerKey:**'SiteId'
}
Schema::create('favorites', function (Blueprint $table) {
$table->integer('lecture_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->timestamps();
$table->primary(['lecture_id', 'user_id']);
$table->foreign('lecture_id')
->references('id')->on('lectures')
->onDelete('cascade');
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
});
see this example
This is the method in the controller:
public function buyConfirm($ad_id)
{
$ad = Ad::find($ad_id);
$sale = new Sale;
$sale->ad_id = $ad->id;
$sale->seller_id = $ad->user->id;
$sale->buyer_id = \Auth::user()->id;
$sale->save();
$x = new Notification;
$x->ad_id = $ad->id;
$x->user_id = $ad->user->id;
$x->type = 'bought';
$x->view = 0;
$x->save();
$ad->delete();
return \Redirect::route('buyContact',$sale->id)->with('message', 'Done');
}
Laravel insert the first row without problems, but the second register not, in the new Notification dont insert if $ad->id but if a send a harcode value like '4' the insert is successfully, what happend whit this?
The Notification migration:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateNotificationsTable extends Migration
{
public function up()
{
Schema::create('notifications', function (Blueprint $table) {
$table->increments('id');
$table->string('type');
$table->integer('user_id')->unsigned();
$table->integer('ad_id')->unsigned();
$table->boolean('view');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('ad_id')->references('id')->on('ads')->onDelete('cascade');
});
}
public function down()
{
Schema::drop('notifications');
}
}
This is the model:
<?php namespace Telovendogdl;
use Illuminate\Database\Eloquent\Model;
class Notification extends Model
{
protected $table = 'notifications';
protected $fillable = ['type','ad_id','user_id','view'];
public function user()
{
return $this->belongsTo('App\User');
}
public function ad()
{
return $this->belongsTo('App\Ad');
}
}
I believe your onDelete('cascade') is messing you up.
Right after creating the Notification, you call $ad->delete(). But your migration contains:
$table->foreign('ad_id')->references('id')->on('ads')->onDelete('cascade');
This means that when an ad is deleted, the notification is also deleted.
It's a table migrated from https://github.com/lucadegasperi/oauth2-server-laravel
In the table oauth_clients, the field data type of id is varchar(40), not int.
$name = Input::get('name');
$id = str_random(40);
$secret = str_random(40);
$client = new oauthClient;
$client->name = $name;
$client->id = $id;
$client->secret = $secret;
$client->save();
After save(); the $client->id become '0', not the string I assigned.
That makes the following relation table save fail.
$endpoint = new OauthClientEndpoint(array('redirect_uri' => Input::get('redirect_uri));
$client->OauthClientEndpoint()->save($endpoint);
I checked the $client->id: after save, it becomes 0 and I get an error including this one:
(SQL: insert into `oauth_client_endpoints` (`redirect_uri`, `client_id`, `updated_at`, `created_at`) values (http://www.xxxxx.com, 0, 2014-09-01 11:10:16, 2014-09-01 11:10:16))
I manually saved an endpoint to prevent this error for now. But how do I resolve this issue?
Here's my model:
class OauthClient extends Eloquent {
protected $table = 'oauth_clients';
public function OauthClientEndpoint(){
return $this->hasOne('OauthClientEndpoint', 'client_id', 'id');
}
}
class OauthClientEndpoint extends Eloquent {
protected $table = 'oauth_client_endpoints';
protected $fillable = array('redirect_uri');
public function OauthClient(){
return $this->belongsTo('OauthClient', 'client_id', 'id');
}
}
class CreateOauthClientsTable extends Migration {
public function up() {
Schema::create('oauth_clients', function (Blueprint $table) {
$table->string('id', 40);
$table->string('secret', 40);
$table->string('name');
$table->timestamps();
$table->unique('id');
$table->unique(array('id', 'secret'));
});
}
public function down() {
Schema::drop('oauth_clients');
}
}
class CreateOauthClientEndpointsTable extends Migration {
public function up() {
Schema::create('oauth_client_endpoints', function (Blueprint $table) {
$table->increments('id');
$table->string('client_id', 40);
$table->string('redirect_uri');
$table->timestamps();
$table->foreign('client_id')
->references('id')->on('oauth_clients')
->onDelete('cascade')
->onUpdate('cascade');
});
}
public function down() {
Schema::table('oauth_client_endpoints', function ($table) {
$table->dropForeign('oauth_client_endpoints_client_id_foreign');
});
Schema::drop('oauth_client_endpoints');
}
}
When you are setting your own ID and not using auto_increment be sure to add public $incrementing = false; to that model. In your case you want:
class OauthClient extends Eloquent {
public $incrementing = false;
protected $table = 'oauth_clients';
public function OauthClientEndpoint(){
return $this->hasOne('OauthClientEndpoint', 'client_id', 'id');
}
}
This is a tiny red block in the huge Laravel documentation:
Note: Typically, your Eloquent models will have auto-incrementing keys. However, if you wish to specify your own keys, set the incrementing property on your model to false.