Answer the question
In order to leave comments, you need to log in
How to merge fields in a table?
Laravel version 5.0.34
I want to display all products that belong to categories.
Please tell me why when calling
$comments = \App\category::find(1)->products()->all();
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class product extends Model {
protected $table = 'products';
public function category()
{
return $this->belongsTo('App\category','id', 'category_id');
}
}
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class category extends Model {
protected $table = 'categories';
public function products()
{
return $this->hasMany('App\product' ,'category_id', 'id');
}
}
<?php namespace App\Http\Controllers;
use App\category;
use App\product;
....
public function categoryItem(category $categoryModel,product $productModel ) {
$comments = \App\category::find(1)->products()->all();
}
CREATE TABLE `products` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`title` VARCHAR(255) NOT NULL DEFAULT '0',
`img` VARCHAR(255) NOT NULL DEFAULT '0',
`intro_text` VARCHAR(255) NOT NULL DEFAULT '0',
`status` INT(1) NOT NULL DEFAULT '0',
`full_text` TEXT NOT NULL,
`slug` VARCHAR(50) NOT NULL,
`price` INT(11) NOT NULL,
`category_id` INT(11) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=6
;
CREATE TABLE `categories` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`title` VARCHAR(255) NOT NULL,
`full_text` TEXT NOT NULL,
`created_at` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
`slug` VARCHAR(50) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=7
;
Answer the question
In order to leave comments, you need to log in
First, check if you have a category with this id.
You no longer need the second moment of all(), since the query is executed by find().
And it's better to organize such a request a little differently:
And one more fix:
<?php namespace App\Http\Controllers;
use App\category;
use App\product;
public function categoryItem(category $categoryModel,product $productModel ) {
$comments = category::with('products')->find($id);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question