I am making a query in Laravel but it is not giving me its one-to-many relationship, here I leave the query and the model
Article Model
class Article extends Model
{
protected $with = ['category'];
protected $fillable = [
'id',
'register_number',
'name',
'quantity',
'category_id',
'created_at',
'updated_at'
];
public function category() {
return $this->belongsTo(Category::class);
}
public function setNameAttribute($value) {
$this->attributes['name'] = strtolower($value);
}
public function getNameAttribute($value) {
return ucwords($value);
}
}
and here I leave the query that I am making, as seen above I have the with attribute that should bring the category
$articles = DB::table('articles')
->whereDate('created_at', '>=', $start_date)
->whereDate('created_at', '<=', $end_date)
->get();
At the end it gives me all the articles but it does not also give me the category
ejm: a list of items like this:
{
"id": 1,
"name": "Prueba",
"register_number": "95ee89fb-bd27-3249-a7d2-086abc57919e",
"quantity": 66,
"category_id": 3,
"created_at": "2019-07-10 05:37:27",
"updated_at": "2019-08-11 15:59:40",
"category": {
"id": 3,
"name": "quos",
"created_at": "2019-08-10 05:37:27",
"updated_at": "2019-08-10 05:37:27"
}
}
It seems to me that the detail of the relationship that you are establishing with Eloquent in your model does not work, is because you are using the queryBuilder, because when using the method
table()
you are indicating that it directly makes a query on that table and since you do not invoke the modelArticle
will not show the categories with which the product is associatedYour query should start like this:
Where we make use of eager loading so that in the same query the categories product of using the relationship
belongsTo()
declared in the body of the Article model class are loaded, where we will pass its name as the method argumentwith()
Eager loading