SQLSTATE[42S22]: Column not found: 1054 Unknown column in laravel - php

I'm trying to make a shopping cart with laravel and am having trouble with one of the methods
this is the error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'pedidos__produtos.pedidos_id' in 'where clause' (SQL: select id_produto, sum(total) as Total, count(1) as qtd from pedidos__produtos where pedidos__produtos.pedidos_id = 1 and pedidos__produtos.pedidos_id is not null group by id_produto order by id_produto desc)
I searched the entire code, but I did not refer this field "pedidos_id" anywhere
This error happens when I call "$pedidos[0]->pedido_produtos," in Carrinhocontroller.php
These are the related methods and migrations:
CarrinhoController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Pedidos;
use Illuminate\Support\Facades\Auth;
class CarrinhoController extends Controller
{
function __construct(){
$this->middleware('auth');
}
public function index(){
$pedidos = Pedidos::where([
'id_user' => Auth::id()
])->get();
dd([
$pedidos,
$pedidos[0]->pedido_produtos,
//$pedidos[0]->pedidos_produtos[0]->produto
]);
return view('carrinho.index', compact('pedidos'));
}
}
Pedidos.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Pedidos extends Model
{
public function pedido_produtos(){
return $this->hasMany('App\Pedidos_Produtos')
->select( \DB::raw('id_produto, sum(total) as Total, count(1) as qtd'))
->groupBy('id_produto')
->orderBy('id_produto', 'desc');
}
}
Pedidos_Produtos.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Pedidos_Produtos extends Model
{
public function produto(){
return $this->belongsTo('App\Produtos', 'id_produto', 'id');
}
}
Migration from Pedidos:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePedidosTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('pedidos', function (Blueprint $table) {
$table->increments('id');
$table->integer('id_user')->unsigned();
$table->foreign('id_user')->references('id')->on('users');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('pedidos');
}
}
and from pedidos_produtos
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePedidosProdutosTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('pedidos__produtos', function (Blueprint $table) {
$table->increments('id');
$table->integer('id_pedido')->unsigned();
$table->integer('id_produto')->unsigned();
$table->decimal('total', 6, 2)->default(0);
$table->timestamps();
$table->foreign('id_pedido')->references('id')->on('pedidos');
$table->foreign('id_produto')->references('id')->on('produtos');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('pedidos__produtos');
}
}
Can Anyone help me with that?

It generates automatically if foreignKey attribute is not defined on hasMany method.
it generates field name from classname_id pattern. Also localKey default value is class PK.
public function hasMany($related, $foreignKey = null, $localKey = null)
You can use like this.
return $this->hasMany('App\Pedidos_Produtos','id_pedido')

The problem you are experiencing is probably to do with this line:
return $this->hasMany('App\Pedidos_Produtos')
If you do not explicitly tell Laravel what the IDs are called on each table when defining a hasMany relationship, it will assume that the id is {table_name}_id which is where the pedidos_id is coming from.
Try adding the foreign and local keys to the hasMany, something like this:
return $this->hasMany('App\Pedidos_Produtos', 'id_pedido', 'id')

Related

Eloquent relation query returning null value

I am trying to get some relational data. All the methods work well but only one method is not working. I am trying to call App\ModeltestMcqQuestion::find(id)->chapterwiseMcqs from tinker, but it is returning null. My database is well populated. I have tried with many id, but nothing is working.
My Models are:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class ChapterwiseMcq extends Model
{
use SoftDeletes;
protected $fillable = [
'topic_id',
'question_type',
'question',
'question_description',
'question_resource',
'a',
'b',
'c',
'd',
'answer',
'answer_description',
'answer_resource',
];
public function topic(){
return $this->belongsTo(Topic::class);
}
public function modeltestMcqAnswers(){
return $this->hasMany(ModeltestMcqAnswer::class);
}
public function modeltestMcqQuestions(){
return $this->hasMany(ModeltestMcqQuestion::class);
}
}
Another Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class ModeltestMcqQuestion extends Model
{
use SoftDeletes;
protected $fillable = [
'modeltest_question_set_id',
'chapterwise_mcq_id',
];
public function modeltestQuestionSet(){
return $this->belongsTo(ModeltestQuestionSet::class);
}
public function chapterwiseMcqs(){
return $this->belongsTo(ChapterwiseMcq::class);
}
}
Migrations:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateChapterwiseMCQSTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('chapterwise_mcqs', function (Blueprint $table) {
$table->id();
$table->foreignId('topic_id')->constrained()->onDelete('cascade')->onUpdate('cascade');
$table->integer('question_type');
$table->string('question');
$table->text('question_description')->nullable();
$table->string('question_resource')->nullable();
$table->string('a');
$table->string('b');
$table->string('c');
$table->string('d');
$table->string('answer');
$table->text('answer_description')->nullable();
$table->string('answer_resource')->nullable();
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('chapterwise_m_c_q_s');
}
}
Another migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateModeltestMcqQuestionsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('modeltest_mcq_questions', function (Blueprint $table) {
$table->id();
$table->foreignId('modeltest_question_set_id')->constrained()->onUpdate('cascade')->onDelete('cascade');
$table->foreignId('chapterwise_mcq_id')->constrained()->onUpdate('cascade')->onDelete('cascade');
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('modeltest_mcq_questions');
}
}
All the relational queries work well except App\ModeltestMcqQuestion::find(id)->chapterwiseMcqs. Can anyone help me what is wrong with the code? Here, id represents id of the model.
I have found a solution. Defining the funtion name caused the problem, I think.
public function chapterwiseMcqs()
Thu function name should be chapterwiseMcq(), not chapterwiseMcqs(). Changing the name worked for me.

Problem with seeding data in pivot table in Laravel

I have a problem while attempting to seed my pivot table in database in Laravel. I get error
Base table or view not found: 1146 Table 'user_cuisines' doesn't exist
And my table name is actually user_cuisine, so it is like for some reason laravel doesn't show that table. I added in my relationships that user_cuisine is pivot table because of alphabet order. Any help is appreciated. Here is my code.
UserCuisineTableSeeder.php
<?php
use App\UserCuisine;
use App\UserProfile;
use Illuminate\Database\Seeder;
class UserCuisineTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$cuisines = UserCuisine::all();
UserProfile::all()->each(function ($userProfile) use ($cuisines) {
$userProfile->cuisines()->attach(
$cuisines->random(rand(1, 12))->pluck('id')->toArray()
);
});
}
}
DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
$this->call(WhitelabelTableSeeder::class);
$this->call(CitiesTableSeeder::class);
$this->call(UserTableSeeder::class);
$this->call(UserProfilePropertiesSeeder::class);
$this->call(UserProfileTableSeeder::class);
$this->call(FieldTableSeeder::class);
$this->call(FieldValueTableSeeder::class);
$this->call(CuisineTableSeeder::class);
$this->call(LiteratureTableSeeder::class);
$this->call(MusicTableSeeder::class);
$this->call(SportTableSeeder::class);
$this->call(TvTableSeeder::class);
$this->call(UserCuisineTableSeeder::class);
$this->call(UserInterestTableSeeder::class);
}
}
UserCuisine.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserCuisine extends Model
{
protected $fillable = [
'name'
];
public function userProfiles()
{
return $this->belongsToMany(UserProfile::class, 'user_cuisine');
}
}
UserProfile.php
<?php
namespace App;
class UserProfile
{
public function user()
{
return $this->belongsTo(User::class);
}
public function cuisines()
{
return $this->belongsToMany(UserCuisine::class, 'user_cuisine');
}
}
user_cuisine_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUserCuisineTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('user_cuisine', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('cuisine_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('user_cuisine');
}
}
cuisine_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCuisineTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('cuisine', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('cuisine');
}
}
Laravel expect the table name to be user_cuisines but you named it user_cuisine without the "s"
You can fix that by changing your migration or adding protected $table = 'user_cuisine'; to your model.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserCuisine extends Model
{
protected $table = 'user_cuisine';
}
As naming convention goes, I would recommend changing the table name 👍
Seems user_cuisines table does not exist, You have created cuisine not user_cuisines
Just put below code in UserCuisine model.
protected $table= 'user_cuisine';
I would recommend always use -m flag while creating a model to avoid these types of errors, for example.
php artisan make:model ModelName -m

hasMany model relation returns empty array. lLaravel Framework 5.5.40

This is my first time posting here, sorry if i input something incorrectly.
So i have Forums.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Forums extends Model
{
protected $table ='forums';
public $primaryKey='id';
public function section()
{
return $this->belongsTo(Section::class,'id');
}
}
and Section.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Section extends Model
{
public function forums()
{
return $this->hasmany(Forums::class,'section_id');
}
}
I fallowed tutorial in which it was shown that using
$section=Section::find($id)->forums;
i should get all the forums that had fk equal to section $id, however ir returns empty array.
I tried to output sql in terminal using:
$order = App\Section::find(2)->forums()->toSql()
where 2 is sections table id and got:
select * from `forums` where `forums`.`section_id` is null and `forums`.`section_id` is not
null"
so no wonder it returns empty array
however if i try to get section related to forum it works perfectly.
How could i fix this?
Changing hasmady to hasMany didn't fix it
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('Forums', function (Blueprint $table) {
$table->increments('id');
$table->string('Name');
$table->string('Description');
$table->integer('topics');
$table->integer('Comments');
$table->integer('Last_Post_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('Forums');
}
}
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddToUsers extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('Forums', function (Blueprint $table)
{
$table->integer('Section_id');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
}
}
can't seem to find sections shema though i have it's table in database or is because that shema isn't in project folder, because im not getting errors that table or col can't be found?

laravel eloquent relation one to many returns null

The product data always return null when i get the incoming_goods data (belongsTo).
Here is my Product Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Product extends Model
{
use SoftDeletes;
protected $guarded = [
'id', 'created_at', 'updated_at', 'deleted_at',
];
public function transaction_details()
{
return $this->hasMany('App\Transaction_detail');
}
public function incoming_goods()
{
return $this->hasMany('App\Incoming_good');
}
}
Here is my Incoming_good Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Incoming_good extends Model
{
protected $guarded = [
'id', 'created_at', 'updated_at',
];
public function product()
{
return $this->belongsTo('App\Product');
}
}
And here is my migration of that two table:
products table Migration:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 50);
$table->integer('price');
$table->integer('stock')->nullable();
$table->integer('available');
$table->string('image1', 190)->nullable();
$table->string('image2', 190)->nullable();
$table->string('image3', 190)->nullable();
$table->string('image4', 190)->nullable();
$table->string('image5', 190)->nullable();
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
incoming_goods migration:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTableIncomingGoods extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('incoming_goods', function (Blueprint $table) {
$table->increments('id');
$table->integer('product_id');
$table->integer('stock');
$table->text('note')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('incoming_goods');
}
}
Here is my code to show incomong_goods data and product (relation belongsTo):
$data = Incoming_good::select('id', 'stock', 'note', 'created_at')->with('product')->get();
I've try to use alies, but still it return the product data null. Hope you can help me :)
In order to match up the eager loaded Products with the Incoming_goods, Laravel needs the foreign key to be selected. Since you did not include the foreign key (product_id) in the select list, Laravel can't match up the related records after retrieving them. So, all your product relationships will be empty. Add in the foreign key to the select list, and you should be good.
$data = Incoming_good::select('id', 'product_id', 'stock', 'note', 'created_at')
->with('product')
->get();

Can I use where in eloquent while giving it an object?

I'm new to Laravel & Eloquent, I'm coming from Django.
In Django I can create a filter on my results and use an object to filter the results...
I'm trying to figure out if I could do this in Laravel/Eloquent also...
Here's what I'm trying to do....
create_messages_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMessagesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('messages', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('user_id');
$table->string('message');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('messages');
}
}
Message.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Message extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
MessageController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Message;
use Illuminate\Support\Facades\Auth;
class MessageController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$messages = Message::where("user", Auth::user())->get();
dd($messages);
return $messages;
}
}
The problem is that when the controller index() function is routed too... I get an error saying "user" column does not exist... and it doesn't but I assumed the models user() function would take care of that and that I would be able to compare it's returning object with Auth::user().
Am I wrong, or am I just doing it wrong?
In the "where" query, the first parameter must be a column in the database. If you want to make use of a "user" column, I'll suggest you add a user column to your table.
I think the auth:user() is to authenticate the current user.
So laravel eloquent is only alerting you that the "user" column does not exist. I will suggest you create a user column, and see what happens next.

Categories