Column not found: 1054 Champ 'posts.categorie_id' inconnu - php

I want to get POSTS from the CATEGORIE i do the relationship HasMany/belongsTo but it gives me error.
Categorie.php
public function posts(){
return $this->hasMany('App\Post');
}
Post.php
public function category(){
return $this->belongsTo('App\Category');
}
SiteController.php
public function getPostsOfCategory($slug){
$categorie=Categorie::where('slug',$slug)->first();
$posts= $categorie->posts()->paginate(4);
$categories=Categorie::all();
return view('site.blog',['posts'=>$posts,'categories'=>$categories]);
}

First of all you called model Categorie but using Category.
return $this->belongsTo('App\Category');
->
return $this->belongsTo('App\Categorie');
This might be not the whole solution.
After that check the name of foreign key column in posts table. And change/add it in database or pass as the second parameter to belongsTo() relation.

The mistake is in your SiteController
public function getPostsOfCategory($slug)
{
$categorie=Categorie::where('slug',$slug)->first();
$posts= $categorie->posts;
$categories=Categorie::all();
return view('site.blog',['posts'=>$posts,'categories'=>$categories]);
}

Related

Retrieving data from hasMany Relationship

I want to show data from 'personas' (parent table) that has at least one 'residente' (child table), its a one to many relationship, and i want to show data of that residente too.
I was trying to do it using the has() method like the laravel documentation says:
https://laravel.com/docs/9.x/eloquent-relationships#querying-relationship-existence
but it does not work.
Models looks like this
//in the Persona class
public function residentes()
{
return $this->hasMany(Residente::class);
}
//in the Residente class
public function persona()
{
return $this->belongsTo(Persona::class);
}
//in the PersonasController
public function index()
{
$personas = Persona::has('residentes')->get();
dd($personas);
}
the Result
enter image description here
//it doesn't get the data from "residentes"
Try :
public function index()
{
$personas = Persona::with('residentes')->get();
dd($personas);
}
If you want to search using some keys inside the residentes relationship you can use whereHas
Persona::with('residentes')
->whereHas('residentes',function($residente){
return $residente->where('column_name',$value);
})->get();
Also try to mention the local_key and the foreign_key in the relationship itself reference : https://laravel.com/docs/9.x/eloquent-relationships
return $this->hasMany(Comment::class, 'foreign_key', 'local_key');
Please try the following in the place of key give actual field names.
//in the Persona class
public function residentes()
{
return $this->hasMany(Residente::class, 'foreign_key', 'local_key');
}
//in the Residente class
public function persona()
{
return $this->belongsTo(Persona::class,'foreign_key', 'owner_key');
}
//in the PersonasController
public function index()
{
$personas = Persona::with('residentes')->get();
foreach($personas as $person){
echo "<pre>";
print_r($person->residentes()->get()->toArray());
}
}

Laravel hasMany and belongsToMany relationship

I have struggled with my Laravel relationships.
So I have 3 tables:
Users
Countries
countries_user
As you can see relation is countries_user. Now every time gives error like:
Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found:
1054 Unknown column 'countries.user_id' in 'where clause' (SQL: select
from countries where countries.user_id = 1 and countries.user_id is not null) in file
C:\xampp\htdocs\gManager\vendor\laravel\framework\src\Illuminate\Database\Connection.php
on line 671
I understand the problem is that it's looking in countries and not in countries_user. How to define where I want to search the relation?
Here is my User model
public function countries()
{
return $this->hasMany('App\Models\Countries');
}
And my Countries Model
public function users()
{
return $this->belongsToMany(User::class);
}
Try specifying the table name
public function users()
{
return $this->belongsToMany(User::class, 'countries_user');
}
And the inverse relation should also be belongsToMany
public function countries()
{
return $this->belongsToMany(Countries::class, 'countries_user');
}
And also specify the table property on Countries model
class Countries extends Model
{
protected $table = 'countries';
//...
}
The countries relationship should be belongsToMany too.
Instead of
public function countries()
{
return $this->hasMany('App\Models\Countries');
}
put
public function countries()
{
return $this->belongsToMany('App\Models\Countries');
}

Retrieving eloquent relationship with laravel

When I try to get the name of the Category from my product, I discovered I had to use a 'C' rather than a 'c' before it retrieved results. However when I try to get the Supplier name, the lowercase s works just fine. I was wondering what is causing this difference. Also if I dd($var), is the relations field expected to be empty. I assumed it would have something related to the relationships defined in my models.
Blade.php
<td>{{$product->Category->name}}</td>
<td>{{$product->salePrice}}</td>
<td>{{$product->stock}}</td>
<td>{{$product->supplier->company_name}}</td>
Product.php
public function category()
{
return $this->belongsTo('App\Category','category');
}
public function supplier()
{
return $this->belongsTo('App\Supplier','supplier_id');
}
Category.php
public function product()
{
return $this->hasMany('App\Product');
}
Supplier.php
public function product()
{
return $this->hasMany('App\Product');
}
You're missing a _id on your Product model:
public function category()
{
return $this->belongsTo('App\Category','category_id');
}
Or leave empty
public function category()
{
return $this->belongsTo('App\Category');
}
In your Controller
public function index()
{
$products = Product::all()->with('category');
return view('your_view', compact('products'));
}
If you dd the products
In your View you will se that the relation has been loaded because of the
Eager Loading
When accessing Eloquent relationships as properties, the relationship data is "lazy loaded". This means the relationship data is not actually loaded until you first access the property. However, Eloquent can "eager load" relationships at the time you query the parent model.
#foreach($products as $product)
<td>{{$product->category->name}}</td>
<td>{{$product->salePrice}}</td>
<td>{{$product->stock}}</td>
<td>{{$product->supplier->company_name}}</td>
#endforeach

Select specific column in laravel eloquent's with method

I am using laravel 5.6 and i want to get user posts with comments (only id field)
User Model
public function posts()
{
return $this->hasMany('App\Post');
}
Post Model
public function user()
{
return $this->belongsTo('App\User');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
Comment Model
public function post()
{
return $this->belongsTo('App\Post');
}
In my controller i am using this code to get user posts with their comments
$posts = $request->user()->posts()->with(['comments' => function($query) {
$query->select(['id']);
}]);
But its not working...
When i comment $query->select(['id']); it works fine but returns Comment model all fields. I want to only select id field.
What i am missing here?
You also have to select the foreign key column (required for matching the results):
$posts = $request->user()->posts()->with('comments:id,post_id');
If you want to only one column, you can use ->pluck('id')
https://laravel.com/docs/5.6/collections#method-pluck

getRouteByKeyName another model laravel

I have two models:
Categories
CategoriesTranslations
In model categories I writed:
public function getRouteKeyName(){
return 'alias';
}
Column alias belogns model CategoriesTranslations.
How I can return alias from model CategoriesTranslations?
My code is not working.
I tryed:
Add getRouteKeyName on CategoriesTranslations:
public function getRouteKeyName(){
return 'alias';
}
And in Categories add:
public function categoryTranslations() {
return $this->hasOne(CategoriesTranslations::class);
}
public function getRouteKeyName() {
return $this->categoryTranslations->getRouteKeyName();
}
I get error Call to a member function getRouteKeyName() on null When want show category by getRouteKeyName. How fix it?
You must use relationships between Categories and CategoriesTranslations.
In your Categories model:
public function categoriesTranslations()
{
return $this->hasMany(CategoriesTranslations::class);
}
public function getRouteKeyName()
{
$this->categoryTranslations->where('locale', Auth::user()->locale)->first()->getRouteKeyName();
}
Now you can call getRouteKeyName() from any instance of the Categories model and it will pull it from the CategoriesTranslations table.
** The potential fix here was adding in the where() statement and the first() method. Change the Auth::user()->locale to wherever you are storing which locale to use.

Categories