I'm using Laravel 8 web api and how can to obtain all the elements or data that belong to the same parent id, that is, I send the category id 3 through the API,
it must return all the products or elements under this id. How can I relate the tables to have that data? and what would be the method or function that should be in the Show($id) function?
I have some code, but it is not working correctly
Here's my code: Document Type Controller:
public function show($id) {
$userWithDoc = User::where('users.document_type_id','=',$id)
->join('document_types', function($join) use($id){
$join->on('document_types.id', '=', 'users.document_type_id');
})->get();
return response()->json($userWithDoc);
}
Model:
class DocumentType extends Model
{
use HasFactory;
protected $fillable = ['DocumentTypeName'];
public function users()
{
return $this->hasMany('App\Models\User');
}
}
Document Type Migration File:
Schema::create('document_types', function (Blueprint $table) {
$table->id();
$table->string('DocumentTypeName');
$table->timestamps();
});
User Migration File:
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('firstName');
$table->string('middleName')->nullable();
$table->string('lastName');
$table->string('userName');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->bigInteger('document_type_id')->unsigned()->default(1);
$table->foreign('document_type_id')
->references('id')
->on('document_types')
->onUpdate('cascade')
->onDelete('cascade');
}
CodePudding user response:
It seems that the join has been over complicated in the show
?
Try with:
public function show($id) {
$userWithDoc = User::where('users.document_type_id', '=', $id)
->join('document_types', 'document_types.id', '=', 'users.document_type_id')
->get();
return response()->json($userWithDoc);
}