I'm trying to display the contents of two related tables, but I don't think I'm getting the relationship right. I have 2 tables, categories and products . The categories table contains the cat_id and cat_name fields . One of the fields in the products table is cat_prod , which stores the same thing as the id_cat field , obviously, being the id of the category to which the product belongs. I haven't migrated any of these models with commands, but I created them directly in phpMyAdmin, and so far I don't know if this gives me any problems.
This is the Category model :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Categoria extends Model
{
use SoftDeletes;
const UPDATED_AT = null;
const CREATED_AT = null;
protected $primaryKey = "id_cat";
public $fillable = ['nom_cat'];
public $incrementing = false;
public $timestamps = false;
}
And this is the Product model :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Producto extends Model
{
use SoftDeletes;
const UPDATED_AT = null;
const CREATED_AT = null;
protected $primaryKey = "id_prod";
public $fillable = ['nom_prod'];
public $incrementing = false;
public $timestamps = false;
//Aqui intento hacer la relacion para tener acceso al atributo NOMBRE de la categoria correspondiente//
public function categoria(){
return $this->hasOne(Categoria::class, 'id_cat', 'cat_prod');
}
}
Once this is done, I try to display the cat_name attribute on the screen
<tbody>
@foreach ($productos as $prod)
<tr>
<td class="body-td">{{$prod->id_prod}}</td>
<td class="body-td">{{$prod->nom_prod}}</td>
<td class="body-td"></td>
<td class="body-td">{{$prod->categoria->nom_cat}}</td> //Esta linea genera el error//
<td class="body-td"></td>
<td class="body-td"></td>
<td class="body-td"></td>
<td class="body-td"></td>
</tr>
@endforeach
</tbody>
If I remove that line, it shows me the rest, but I have not been able to solve this error
Undefined property: stdClass::$category
This is the query with which I get the attributes of the product table :
public function getProductos(){
$productos = DB::table('productos')->select('*')
->whereNull('deleted_at')
->get();
return view('admin.productos.home', compact('productos'));
}
Regarding this query, I can display the obtained data without any problem.
And according to the video that I am following, with this code it is enough to obtain the data that I want to show:
//Aqui intento hacer la relacion para tener acceso al atributo NOMBRE de la categoria correspondiente//
public function categoria(){
return $this->hasOne(Categoria::class, 'id_cat', 'cat_prod');
}
(I already referenced this code snippet above)
What mistake am I making? How can I solve it?
Thanks in advance.