I want to display all liked products of a specific user from the database, but I'm getting an error Integrity constraint violation: 1052 Column 'deleted_at' in where clause is ambiguous .How can I display all liked products of specific user?
Like.php
class Like extends Model
{
use SoftDeletes;
protected $table = 'likeables';
protected $fillable = [
'user_id',
'likeable_id',
'likeable_type',
];
/**
* Get all of the products that are assigned this like.
*/
public function products()
{
return $this->morphedByMany('App\Product', 'likeable');
}
}
Product.php
public function likes()
{
return $this->morphToMany('App\User', 'likeable')->whereDeletedAt(null);
}
public function getIsLikedAttribute()
{
$like = $this->likes()->whereUserId(Auth::id())->first();
return (!is_null($like)) ? true : false;
}
User.php
public function likedProducts()
{
return $this->morphedByMany('App\Product', 'likeable')->whereDeletedAt(null);
}
Blade file
#foreach (Auth::user()->likedProducts as $product)
<h2>{{ $product->price }}</h2>
#endforeach
You have two deleted_at column in users table and products table. That's why the error . change your likedProducts function like this
public function likedProducts()
{
return $this->morphedByMany('App\Product', 'likeable')->whereNull('products.deleted_at');
}
Related
I have synced data where I attach some products to another one as related ones, save and sync method works just fine, my issue in edit part.
I get this error when I try to load my product edit page:
SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'product_relatives' (SQL: select `product_relatives`.*, `product_relatives`.`product_id` as `pivot_product_id`, `product_relatives`.`relatives_id` as `pivot_relatives_id` from `product_relatives` inner join `product_relatives` on `product_relatives`.`id` = `product_relatives`.`relatives_id` where `product_relatives`.`product_id` = 49)
Codes
this is my edit function
public function edit($id)
{
$product = Product::findOrFail($id);
//another synced data and how i retrieve them
$suboptions = Suboption::all();
$suboptions2 = array();
foreach($suboptions as $suboption) {
$suboptions2[$suboption->id] = $suboption->title;
}
// my issue comes from here
$relatives = ProductRelative::all();
$relatives2 = array();
foreach($relatives as $relative) {
$relatives2[$relative->id] = $relative->title;
}
return view('admin.products.edit', compact('product','suboptions2', 'relatives2'));
}
blade code
{{ Form::label('relatives', 'Relative Products') }}
{{Form::select('relatives[]', $relatives2, null, ['class' => 'form-control tagsselector', 'multiple' => 'multiple'])}}
product model
public function relatives()
{
return $this->belongsToMany(ProductRelative::class, 'product_relatives', 'product_id', 'relatives_id');
}
relatives model
public $timestamps = false;
protected $table = 'product_relatives';
public $fillable = ['product_id', 'relatives_id'];
public function products()
{
return $this->belongsToMany(Product::class);
}
any idea how to fix that?
The SQL statement that is failing makes perfect sense. It is attempting to join the table product_relatives to the product_relatives table. So the error Not unique table or alias being thrown makes sense based on the query alone.
The next step is to try and think of reasons Laravel might be getting mixed up here.
Since you are trying to create a belongsToMany with the same model, you'll need these tables
products
product_relatives
Now, you only need to create one model:
Product
Your Product model should contain:
public function relatives()
{
return $this->belongsToMany(Product::class, 'product_relative', 'product_id', 'relative_id');
}
Your ProductRelative model should contain:
public function product()
{
return $this->belongsTo(Product::class, 'product_id');
}
public function relative()
{
return $this->belongsTo(Product::class, 'relatives_id');
}
The issue was happening because you were using the ProductRelative model as a pivot table, and tried to create a BelongsToMany relationship within it using the same table name as the model itself.
I'm trying to show a list of contacts for the logged in user. But obviously I'm doing something wrong.
I get a error on the contacts list page:
Trying to get property 'name' of non-object
User.php
public function contacts()
{
return $this->belongsToMany(Contact::class);
}
Contact.php
public function users()
{
return $this->belongsToMany(User::class);
}
ContactsController.php
public function index()
{
//
$user = Auth::user();
$user_contacts = $user->contacts()
return view('contacts.list')->with('contacts', $user_contacts);
}
list.blade.php
#foreach ($contacts as $contact)
* {{ $contact->name }} <br>
#endforeach
Table schema:
contacts:
id
created_at
updated_at
name
address
users:
id
name
password
remember_token
created_at
updated_at
contact_user:
contact_id
user_id
If you want to access pivot properties of your many to many relationship table u can access with pivot
#foreach ($contacts as $contact)
* {{ $contact->pivot->name }} <br>
#endforeach
Also creates a relatioship between contact and users
public function contacts()
{
return $this->belongsToMany(Contat::class)->withPivot(['your', 'pivot','columns']);
}
Hope this helps
In your controller you have the following;
public function index()
{
$user = Auth::user();
$user_contacts = $user->contacts()
return view('contacts.list')->with('contacts', $user_contacts);
}
It needs to be the following;
public function index()
{
$user = Auth::user();
$user_contacts = $user->contacts
return view('contacts.list')->with('contacts', $user_contacts);
}
Using $user->contacts()(method) will return an instance of the query builder for that relationship, where as $user->contacts(property) will return a collection with results from a select query.
You must return your pivot table's data in the relation as below:
public function contacts()
{
return $this->belongsToMany(Contat::class)->withPivot(['your', 'pivot','columns']);
}
And you must get relation data like below:
$user_contacts = $user->contacts // Not $user->contacts()
In my application, Users can have many products. Now, i am trying to display the users phone number for a every displayed products.
In my products table, there is a column user_id for the respective users.
This is how my model looks like
User Model
public function products()
{
return $this->belongsTo('Models\Database\User','user_id');
}
Product Model
class Product extends BaseModel
{
protected $fillable = ['user_id','type', 'name', 'slug', 'sku', 'description',
'status', 'in_stock', 'track_stock', 'qty', 'is_taxable', 'page_title', 'page_description'];
// protected $guarded = ['id'];
public static function getCollection()
{
$model = new static;
$products = $model->all();
$productCollection = new ProductCollection();
$productCollection->setCollection($products);
return $productCollection;
}
public function users()
{
return $this->hasMany('\Models\Database\Product');
//->withTimestamps();
}
public function categories()
{
return $this->belongsToMany(Category::class);
}
public function reviews()
{
return $this->hasMany(Review::class);
}
public function prices()
{
return $this->hasMany(ProductPrice::class);
}
public function orders()
{
return $this->hasMany(Order::class);
}
public function users()
{
return $this->hasMany('Models\Database\Product');
}
And in my view, this is how i try to get the respective user's phone number
<p>{{$product->users->phone}}</p>
But i get an error like
SQLSTATE[42S22]: Column not found: 1054 Unknown column
'products.product_id' in 'where clause' (SQL: select * from products
where products.product_id = 1 and products.product_id is not
null)
You should do:
User Model
public function products()
{
return $this->hasMany('Models\Database\Product');
}
Product Model
public function user()
{
return $this->belongsTo('Models\Database\User');
}
In your blade:
{{ $product->user->phone }}
You have got your relationship models inverted,
change them:
In your User model:
public function products()
{
return $this->hasMany('Models\Database\Product');
}
In your Product model:
public function user()
{
return $this->belongsTo('Models\Database\User','user_id');
}
And then you could access the properties like:
<p>{{$product->user->phone}}</p>
Link to the Docs
I mix a little bit with the query in laravel.
I have a list of articles. I would like to get the datas from the author of this article.
Relation model Article
public function author()
{
return $this->belongsTo('App\Models\Author');
}
Relation model Author
public function articles()
{
return $this->hasMany('App\Models\Article');
}
I try this $author = Author::with('articles')->first();
this :
$author = Author::whereHas('articles', function ($query){
$query->where('id', '1');
});
And many others tests, but I doesn't understand all.
My method in my controller :
protected function index()
{
$articles = Article::published()->paginate(8);
return view('pages.blog', [
'articles' => $articles,
]);
}
And above all, how do I display the correct information in my view in my foreach?
Thank you !
To solve the problem you have to define the relationships in the following way.
Article class define, based on the following table structure:
articles {
id : integer [primary key],
...,
author_id : integer [foreign key]
}
class Article extends Illuminate\Database\Eloquent\Model {
protected $table = "articles";
// HERE YOUR CLASS CODE
public function author() {
return $this->belongsTo("Author", "author_id", "id");
}
}
Author class define, based on the following table structure:
authors {
id : integer [primary key],
...
}
class Author extends Illuminate\Database\Eloquent\Model {
protected $table = "authors";
// HERE YOUR CLASS CODE
public function articles() {
return $this->hasMany("Article", "author_id", "id");
}
}
When you use the method belongsTo and hasMany, it is better indicate the label of the external key and the local key.
To display information in your view you have to follow the example:
#foreach ($articles as $article)
<p>Id {{ $article->id }}</p>
...
#endforeach
For more information :
https://laravel.com/docs/5.4/eloquent-relationships
https://laravel.com/docs/5.4/blade
This is my Items model . Now i want to add a new item but i get this error: SQLSTATE[23000]: Integrity constraint violation: 1048
<?php
class Items extends Eloquent
{
protected $guarded = [
'id',
];
protected $fillable = [
'name',
'description',
'price',
'brand',
];
protected $table = 'items';
public function user()
{
return $this->hasOne('User', 'user_ID', 'id');
}
public function size()
{
return DB::table('sizes')->select('size')
->where('id', $this->size_ID)->first()->size;
}
public function color()
{
return DB::table('colors')->select('color')
->where('id', $this->color_ID)->first()->color;
}
public function condition()
{
return DB::table('conditions')->select('type')
->where('id', $this->condition_ID)->first()->type;
}
public function category()
{
return DB::table('categories')->select('category')
->where('id', $this->category_ID)->first()->category;
}
public function images()
{
return DB::table('images')->select('image')
->where('item_id', $this->id)->first()->image;
}
}
And this is my post method to save item.
public function store()
{
$item = new Items;
$item->user_ID = Auth::id();
$item->name = Input::get('name');
$item->description = Input::get('description');
$item->price = Input::get('price');
$item->brand = Input::get('brand');
$item->category = Input::get('Category');
$item->condition = Input::get('Condition');
$item->color = Input::get('Color');
$item->save();
}
Here is a picture of category table , condition and color table has the same logic.
http://imgur.com/9NCMYui
You are creating a relationship between User and Item while not using it.
You can set the populate the relationship manually by filling in the id yourself, but then you don't use the power of the Eloquent ORM.
What I would suggest is getting the current user.
And saving it like this.
$item->user()->save($user);
I suggest for the name of the class Item and not Items.
I find it having much more logic and so do most of the programmers.
The table can still be called items.