Column not found - Laravel whereHas error - php

I'm having a hard time resolving this error.
My models:
User Model:
class User extends Model{
public function requests()
{
return $this->hasMany('App\Models\TeamRequest','requested_user_id');
}
}
TeamRequest Model:
class TeamRequest extends Model {
public function requested_user()
{
return $this->belongsTo('App\Models\User', 'requested_user_id');
}
}
Now, I am trying this query:
UserModel::whereHas('requests',function($query) use ($team_id){
$query->where('team_id',$team_id)
->get();
});
And, I'm getting an error:
Column not found: 1054 Unknown column 'users.id' in 'where clause'
(SQL: select count(*) from team_requests where
team_requests.requested_user_id = users.id)
Why am I getting this error?
Schema:
users table
primary key - id
varchar - email
varchar - password
team_requests table
primary key - id
integer - requested_user_id
I have other columns but I believe they do are not of effect.

Your problem is that you're calling get() inside the closure passed to your whereHas(). The closure is used to add constraints to a subquery that will be used to determine if your user has requests. You're only supposed to add constraints to the query inside the closure, you don't want to actually execute that query. If you execute the query inside the closure, you'll get an error (as you've seen) because it is supposed to be a subquery, and does not have all the information required to execute properly.
Your code should be:
UserModel::whereHas('requests', function ($query) use ($team_id) {
$query->where('team_id', $team_id);
});

Related

Why my relation in Laravel are working backwards when I try to get an one to one associated value?

I got this error
Facade\Ignition\Exceptions\ViewException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'categories.product_id' in 'where clause' (SQL: select * from `categories` where `categories`.`product_id` = 2 and `categories`.`product_id` is not null limit 1) (View: /home/osboxes/shakira/resources/views/products/index.blade.php)
But my models and migrations are just fine. I have to erase migrations also from the database table and yes, I have my category_id in the produc table.
I'm trying to show the category in the index view.
Please share your information completely so people can understand and help you.
I guess you defined your relation backward in your models.
They should be like this:
class Product extends Model
{
public function category()
{
return $this->belongsTo(Product::class);
}
}
class Category extends Model
{
public function products()
{
return $this->hasMany(Category::class);
}
}

Eager Loading is not working laravel 5.3

I have three related models.
1.User model
public function users_wishlst(){
return $this->hasMany('App\Users_wishlst');
}
2.Product Model
public function users_wishlst(){
return $this->belongsTo('App\Users_wishlst');
}
3.Users_wishlst model
public function user(){
return $this->belongsTo('App\User');
}
public function product(){
return $this->hasMany('App\Product');
}
in users_wishlsts table i have the followibg columns
id
user_id
product_id
I want to get the product info of an users wishlist. I have tried this
public function showWishList(){
$id= Auth::id();
$WishList = wishlist::with('product')->where(['user_id'=>$id])->get();
return json_encode($WishList);
}
But this gives me the following error
SQLSTATE[42S22]: Column not found: 1054 Unknown column
'products.users_wishlst_id' in 'where clause' (SQL: select * from
products where products.users_wishlst_id in (1, 2, 3))
what is the problem
Without knowing all about your database structure this seems like a problem with your foreign keys. Eloquent tries to automatically guess the key. Based on the error it seems like your products table doesn't contain a users_wishlst_id column (maybe you named it different?). Try looking at you Database and give Laravel the correct foreign_key.
https://laravel.com/docs/5.3/eloquent-relationships#one-to-many

Laravel 5.3 Eloquent & Relationship

I have a record model and status model. Which each record has status can be "approved", "disapproved" or "in process" which is stored in the status model that connected trough status_id in the record model.
This is my model & their relationship.
Records(id, user_id, status_id, note, date, timestamp)
function status()
{
return $this->hasOne('App\Status');
}
Statuses(id, name)
function record()
{
return $this->belongsToMany('App\Record');
}
I would like to callback like this on my view $records->status->name. But it gives error
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Statuses.record_id' in 'where clause' (SQL: select * from `statuses` where `statuses`.`record_id` = 3 and `statuses`.`record_id` is not null limit 1)
I try to to play the relationship & the callback but it not work. Is it possible to do that? Or better i just save the status directly on the record table without using the status record. Thank you.
You have the relationships reversed. Can you try the following instead:
class Record extends Model
{
public function status()
{
return $this->belongsTo('App\Status');
}
}
class Status extends Model
{
public function records()
{
return $this->hasMany('App\Record');
}
}
I think you are going for a 'One To Many', rather than a 'Many To Many' relationship.
Try the following instead:
Records(id, user_id, status_id, note, date, timestamp)
function status()
{
return $this->belongsTo('App\Status');
}
Statuses(id, name)
function record()
{
return $this->hasMany('App\Record');
}
Define hasOne Relationship on Records
Records(id, user_id, status_id, note, date, timestamp)
function status(){
return $this->hasOne('App\Status','id','status_id');
}
and hasMany Relationship on Status
Statuses(id, name)
function record(){
return $this->hasMany('App\Record','status_id','id');
}
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Statuses.record_id' in 'where clause' (SQL: select * from `statuses` where `statuses`.`record_id` = 3 and `statuses`.`record_id` is not null limit 1)
According to the Error! It says that you don't have records_id in your status table. So add it.
For this to work on You should have a unsigned integer named as record_id in your Status Migration.
$table->unsignedInteger('record_id')->references('id')->on('records'); //This will work as the foreign key to find the respective Status.
After editing the migration file you'll have to rollback migrations.
In terminal at your project directory,
php artisan migrate:rollback
If you could add the migrations as well, It will be easier to point out.
model:Record
Records(id,user_id,status_id,note)
function status(){
return $this->belongsTo('App\Status','id);
}
model:Status
Status(id,name)
function record(){
return $this->hasmany('App\Record','id','status_id');
}
Try this relation it will work

Laravel 5 - Find Fields on "MorphOne" Relationship

I'm quite new to Laravel and I'm now facing this issue while trying to create a query:
I have the following Morphable classes:
\App\User
class User {
public function userable()
{
return $this->morphTo();
}
}
\App\Distributor
class Distributor {
public function user()
{
return $this->morphOne('App\User', 'userable');
}
}
user table has the fields: name, email, status, userable_type and userable_id.
distributor table has the fields: store_code and location_id.
By using Eloquent, i need to start the query from Distributor model and select only the following fields: 'name, email, store_code'.
I'm trying the following, but laravel says user.name doesn't exists :(
$queryBuilder = \App\Distributor::has('user');
$queryBuilder->select(['user.name']);
$queryBuilder->get();
QueryException in Connection.php line 651:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user.name' in 'field list' (SQL: select user.name from distributor where (select count(*) from user where user.userable_id = distributor.id and user.userable_type = App\Distributor and user.deleted_at is null) >= 1)
I was able to achieve my goal forcing the join relationship, but this seems wrong, I think Eloquent is able to find the relation by itself as the Morph relationship is specified in the Model.
Just for record, this works good:
$queryBuilder = \App\Distributor::has('user');
$queryBuilder->join('user', function($join) {
$join->on('userable_id', '=', 'distributor.id')
->where('userable_type', '=', \App\Distributor::class);
});
$queryBuilder->select(['user.name']);
$queryBuilder->get();
Also, since its a one-to-one like relationship, sometimes I'll need to order the results using one of the users columns
But I need another way to do it without forcing the join, something clean as the first example.
read about with() function in the docs
$queryBuilder->select('id','store_code');
$queryBuilder = \App\Distributor::with(['user'=>function($query){
$query->select('id','name','email')
}]);
$queryBuilder->has('user');
$queryBuilder->get();

Getting to use Eloquent hasMany() relationship

I have a table of categories in which my categories and their title and thumbnails are stored.
I have another table in which images are stored.
The third table is a joint table. I store in each record of it, the id of the image and the id of the category.
Table Schema:
id
cat_id
item_id
Now I want to get a cat_id by query_string and then pass it to the function for it to get the list of all images with this category in the database.
I'm confused about how to write the method. I have written the following method for CategoryList model which throws error:
class CategoryList extends Eloquent
{
protected $table = "categories_list";
function Images ()
{
return $this->hasMany("Image", 'id');
}
}
And here is the usage in the Image model:
return CategoryList::Images()->where("cat_id", '=', $catid)->get()->toArray();
But it throws the following error:
{"error":{"type":"Illuminate\\Database\\QueryException","message":"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'cat_id' in 'where clause' (SQL: select * from `images` where `images`.`id` is null and `cat_id` = 19)","file":"C:\\wamp\\www\\aone\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Connection.php","line":539}}
class Category extends Eloquent {
public function images()
{
return $this->belongsToMany('Image');
}
}
Then do:
$images= Categorie::find($catid)->images;
In this case, your pivot table is 'category_image', but if you need to choose another name, it must be specified
return $this->belongsToMany('Image', 'your_pivot_table_name', 'cat_id', 'item_id');
Please visit http://laravel.com/docs/eloquent#many-to-many for more information

Categories