I don't use 'id' column in DB.
Instead, I use a composite primary key user_id + tmdb_id.
If I add new record like this:
$movie = new Movie();
$movie->user_id = 1;
$movie->tmdb_id = 2;
$movie->ratio = 3;
$movie->save();
it works fine!
But if I try to edit an existing record like this:
$movie = Movie::where([
'user_id' => 1,
'tmdb_id' => 2,
])->first();
$movie->ratio = 4;
$movie->save();
Then I have the error:
Unknown column 'id' in 'where clause'.
The migration file looks like this:
public function up()
{
Schema::create('movies', function (Blueprint $table) {
$table->integer('user_id')->unsigned();
$table->integer('tmdb_id')->unsigned();
$table->tinyInteger('ratio');
// composite primary key
$table->primary(['user_id', 'tmdb_id']);
});
}
Laravel doesn't support composite primary keys.
You have to use an additional package like https://github.com/mpociot/laravel-composite-key.
Related
I'm trying to update the data of pivot table (i want to change product in the order)
I have :
-product table:
id
name
product_price
created_at
updated_at
-order table:
id
status
user_id
created_at
updated_at
-order_products table:
order_id
product_id
product_price
count
created_at
updated_at
in Order model:
public function product(){
return $this->belongsToMany('App\Product')->withPivot('count');
}
in Prodect model:
public function order(){
return $this->belongsToMany('App\Order');
}
in controller:
public function EditOrder(Request $request , $id){
$order = Order::find($id);
$order->status = $request->status;
$order->user_id = $request->user_id;
$order->update();
$product_ids = $request->products;
$selectedItems = [];
foreach ( $product_ids as $key => $productId) {
$id1 = $key['product_id'];
$product = Product ::find($id);
$count = $key['count'];
$selectedItems[$productId] = ['product_id' => $id1 ];
$selectedItems[$productId] = ['count' => $count];
$selectedItems[$productId] = ['order_id' => $order->id];
$selectedItems[$productId] = ['price' => $product->product_price];
$order->product()->updateExistingPivot($selectedItems);
}
return response()->json([
'message' => 'Success'
],200);
i faced this error :
Illegal offset type in file C:\Users\Acer\Documents\GitHub\easyrest\app\Http\Controllers\ResturantController.php on line 80
I want to update product_id and count in order_products
updateExistingPivot() expects 2 params, the first being the id of the relationship you want to update, the second being the array of columns you wish to update. You're not passing an id, so it's trying to use your array as the id, which is why you're getting the error. Fix your logic:
foreach($product_ids as $key => $productId) {
$id1 = $key['product_id'];
$product = Product::find($id);
$count = $key['count'];
$selectedItems[$productId] = ['product_id' => $id1];
$selectedItems[$productId] = ['count' => $count];
// $selectedItems[$productId] = ['order_id' => $order->id]; // [1]
$selectedItems[$productId] = ['price' => $product->product_price];
$order->product()->updateExistingPivot($productId, $selectedItems[$productId]); // [2]
}
[1]: You can omit order_id; $order->product()->updateExistingPivot() already knows the order_id and you're not updating it, so it's redundant.
[2]: You don't want to pass the entire $selectedItems array, only the sub-array contained in $selectedItems[$productId]
By passing $productId as the first argument of updateExistingPivot(), Laravel knows what row you want to update, and will use the array keys in $selectedItems[$productId] to determine which columns to update to what. I don't know if this will actually update product_id, but if it doesn't, you may need to detach() then attach() the data instead:
foreach($product_ids as $key => $productId) {
$selectedItems[$id1] = ['count' => $count];
$selectedItems[$id1] = ['price' => $product->product_price];
$order->products()->detach($productId);
$order->products()->attach($id1, $selectedItems[$id1]);
}
I need to update the database table according to the edited data.
controller
public function update(Request $request)
{
$subscriptionplan = SubscriptionPlan::find($request->id);
$subscriptionplan->update($request->all());
return back();
}
But nothing happens when I submit the form. When I use dd($request->all()); at the beginning of the function, it correctly shows the edited data as follows.
array:10 [▼
"_method" => "patch"
"_token" => "gOCL4dK6TfIgs75wV87RdHpFZkD7rBpaJBxJbLHF"
"editname" => "SUP_EVA_001"
"editdesc" => "des"
"editprice" => "1000.050"
"editlimit" => "1"
"editperunit" => "20.000"
"editexceedunit" => "30.000"
"productid" => "1"
"id" => "1"
]
But database has not been updated.
My table name is Table: subscription_plans and model is SubscriptionPlan
These are the table columns:
protected $fillable = [
'name',
'description',
'price',
'usage_limit',
'charge_per_unit',
'charge_per_unit_exceed',
'is_limit_exceed_considered',
'product_id'
];
Any idea on how to solve it or what I have done wrong?
If your solution did not work, try the 1by1 like this.
public function update(Request $request)
{
$subscriptionplan = SubscriptionPlan::find($request->id);
$subscriptionplan->_method = $request->_method;
$subscriptionplan->_token = $request->_token;
$subscriptionplan->editname = $request->editname;
$subscriptionplan->editdesc = $request->editdesc;
$subscriptionplan->editprice = $request->editprice;
$subscriptionplan->editlimit = $request->editlimit;
$subscriptionplan->editperunit = $request->editperunit;
$subscriptionplan->editexceedunit = $request->editexceedunit;
$subscriptionplan->productid = $request->productid;
$subscriptionplan->save();
return back();
}
In order for Laravel to automatically fill the model attributes, the indexes of the array passed to the fill method must correspond to your model attributes names.
Also, instead of
$subscriptionplan->update($request->all());
Use
$subscriptionplan->fill($request->all());
Then save the subscription plan with $subscriptionplan->save();
I am trying to insert into 2 different tables(House and Contact) using a single method.
public function store(HouseRequest $request){
$dataForm = $request->all();
$house = House::create($dataForm); //Insert into House table
$contact = $house->contact()->create($dataForm['contact']); //Insert into Contact table
return back('dashboard/houses')->with('message', 'Success');
}
Here is my table Contact:
Schema::create('contacts', function (Blueprint $table) {
$table->integer('house_id')->unsigned();
$table->string('name', 255);
$table->char('phone', 11);
$table->timestamps();
$table->foreign('house_id')->references('id')->on('houses')->onDelete('cascade')
}
House Model:
public function contact(){
return $this->hasOne(Contact::class);
}
It works fine (inserts into both tables), but after submitting the form, I got this:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from contacts where id = 0 limit 1)
I don't know why it is running the query above. How can I get rid of this error?
You just forgot to add a column for ids add $table->increments('id'); in your migration :
Schema::create('contacts', function (Blueprint $table) {
$table->increments('id');
$table->integer('house_id')->unsigned();
$table->string('name', 255);
$table->char('phone', 11);
$table->timestamps();
$table->foreign('house_id')->references('id')->on('houses')->onDelete('cascade')
}
let data = require('./../../config/db')
let connection = data.connection
let sequelize = data.sequelize
let sql = function(){
let clubMembers = connection.define('club_members',{
position:{
type :sequelize.ENUM('President','Treasurer') ,
allowNull : false
}
},
{
classMethods : {
associate : function(models){
let clubMembers = models.club_members
let club = models.club
let student = models.student
club.hasMany(clubMembers,{
foreignKey : "club_id"
})
student.hasMany(clubMembers,{
foreignKey : "student_id"
})
}
}
}
);
return clubMembers;
}
module.exports = sql;
I dont need id attribute in this table but sequelize automatically creates it . And combination of both the foreign keys should be treated as primary key i.e composite primary key .
You should use belongsToMany in the associate function
associate: function(models){
models.club.belongsToMany(models.student, { through: models.club_members, foreignKey: 'club_id' });
models.student.belongsToMany(models.club, { through: models.club_members, foreignKey: 'student_id' });
}
This would create the club_members table with composite primary key consisting of club_id and student_id, without the default id column.
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!