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
Related
I have 2 models in my app, 'Subject' & 'Professor' (each Subject belongs to many Professors).
I made the many-to-many relation between two model using belongsToMany(). belongsToMany() doesn't work.
I'm trying to get data like this:
$subjects = Subject::with(["professors"])->whereHas("professors", function ($q){ $q->where("id", \request("professor_id")); })->get();
Error:
"SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select * from `subjects` where exists (select * from `professors` inner join `subjects_of_professor` on `professors`.`id` = `subjects_of_professor`.`professor_id` where `subjects`.`id` = `subjects_of_professor`.`subject_id` and `id` = 39))",
Does anyone know where did I make a mistake?
Here's the code to Models:
class Subject extends Model
{
public function professors(): BelongsToMany
{
return $this->belongsToMany(Professor::class, "subjects_of_professor");
}
}
class Professor extends Model
{
public function subjects(): BelongsToMany
{
return $this->belongsToMany(Subject::class, "subjects_of_professor");
}
}
And here is my database structure:
subjects:
id
title
subjects_of_professor:
id
subject_id
professor_id
professors:
id
name
description
I'm found mistake, i was needed to add table in my code, when i trying to get data:
$subjects = Subject::whereHas("professors", function ($q){ $q->where("professors.id", \request("professor_id")); })->get();
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);
}
}
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
How can I echo category name when in Urls view? I get this error:
Column not found: 1054 Unknown column 'categories.url_id' in 'where clause'
(SQL: select * from `categories` where `categories`.`url_id` = 23 and `categories`.`url_id` is not null limit 1
I believe the query should be something like this
SELECT * FROM categories WHERE categories.id = 1
Urls table
id | url | category_id
1 www.asdf.com 1
Categories table
id | category
1 Something
Migration for adding column Category_id to Urls table
public function up()
{
Schema::table('urls', function(Blueprint $table){
$table->integer('category_id')->unsigned()->nullable();
$table->foreign('category_id')->references('id')->on('urls');
});
}
(hm I believe I need to fix this and put references('id')->on('categories') )
Url model
class Url extends Model
{
protected $table = 'urls';
public function category()
{
return $this->hasOne('App\Category');
}
}
Url index controller
$urls = URL::paginate(100)
return view('urls.index')->with('urls', $urls);
Urls.index view
{{ $url->category->category }}
If I change Url model to this
public function category()
{
return $this->belongsTo('App\Category');
}
and when I do var_dump($url->category), the correct SQL query is generated:
select * from `categories` where `categories`.`id` = '1' limit 1
but I still can't get column name with {{ $url->category->category }}
because error is Trying to get property of non-object
Use belongsTo() relationship instead of hasOne():
public function category()
{
return $this->belongsTo('App\Category');
}
A Venue has many Subscriptions.
A Subscription has many Subscribers (User).
Theres a pivot table, containing the relation between user_id and subscription_id.
How can I get all Subscribers from a Venue?
I have tried with:
class Venue {
/**
* Members
*/
public function members() {
return $this->hasManyThrough('App\User', 'App\Subscription');
}
}
But it fails with MySQL error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.subscription_id' in 'on clause' (SQL: select `users`.*, `sub
scriptions`.`venue_id` from `users` inner join `subscriptions` on `subscriptions`.`id` = `users`.`subscription_id` where `
users`.`deleted_at` is null and `subscriptions`.`venue_id` = 1)
How my Subscription model look:
`Subscription`
class Subscription extends Model {
protected $table = 'subscriptions';
/**
* Subscripers
*/
public function subscribers() {
return $this->belongsToMany('App\User');
}
/**
* Venue
*/
public function venue() {
return $this->belongsTo('Venue');
}
}
Simple question: Why are you using a third model for Subscriptions? It sounds like a normal n:m relation between User and Venue, as already written in the comments above.
class User {
public function venues() {
return $this->belongsToMany('App\Venue');
}
}
class Venue {
public function users() {
return $this->belongsToMany('App\User');
}
}
This constellation actually needs three tables, which are (i gave each model a column name):
users
- id
- name
venues
- id
- name
user_venue
- user_id
- venue_id
But to access the relations, you can simply use the Eloquent magic:
// List of all venues (as Venue models) that are in relation with User with id $id
$venues = User::find($id)->venues()->get();
// Returns the alphabetically first user that has a relation with Venue with id $id
$user = Venue::find($id)->users()->orderBy('name', 'asc')->first();
If you need to store additional information in the pivot table (e.g. when the relation has been established), you can use additional pivot fields:
user_venue
- user_id
- venue_id
- created_at
class User {
public function venues() {
return $this->belongsToMany('App\Venue')->withPivot('created_at');
}
}
class Venue {
public function users() {
return $this->belongsToMany('App\User')->withPivot('created_at');
}
}
// Returns the date of the relations establishment for the alphabetically
// first Venue the User with id $id has a relation to
$created_at = User::find($id)->venues()->orderBy('name', 'asc')->first()->pivot->created_at;
I've never tried to do whatever you are trying to do there, because it seems (with the current information) conceptually wrong. I also don't know if it is possible to set up an own model for a pivot table, but I think it should work if the pivot table has an own primary id column. It could probably be helpful if you've a third model that needs to be connected with a connection of two others, but normally that doesn't happen. So try it with pivot tables, like shown above, first.
Alright, I still don't see a good use case for this, but I can provide you a query that works. Unfortunately I wasn't able to get an Eloquent query working, but the solution should be still fine though.
class Venue {
public function members($distinct = true) {
$query = User::select('users.*')
->join('subscription_user', 'subscription_user.user_id', '=', 'users.id')
->join('subscriptions', 'subscriptions.id', '=', 'subscription_user.subscription_id')
->where('subscriptions.venue_id', '=', $this->id);
if($distinct === true) {
$query->distinct();
}
return $query;
}
}
The relation can be queried just as normal:
Venue::find($id)->members()->get()
// or with duplicate members
Venue::find($id)->members(false)->get()