0

I have the following DB schema Products and their categories.

I have created Model for both tables in Laravel called Categorie and Product

class product extends Model
{
use HasFactory;
}

categorie

class categorie extends Model
{
// tried by adding this code in product model
use HasFactory;
protected $primaryKey = 'CategoryID';
//also tried without translation...
public static function translateColumn(string $column)
{
    switch ($column) {
        case 'id':
            return 'CategoryID';
        default:
            return $column;
    }
}

function categorie(){
    return $this->hasMany('App\Models\categorie');
}
}

fetch data

function fetchData(){
    return categorie::find(1)->categorie;
}

I am facing the following exception SQL Exception

I have tried many ways but I can't found a way to run correct query.

I do not want to change DB columns name like change CategoryID to id Only use of model to do this stuff. Cannot use DB class to build query.

If this is possible then how and if its not possible then tell me...

NOTE: I am learning this and want to know if this possible then how... I just don't need some alternate solution... I know alternatives...

Usman Khan
  • 56
  • 8

1 Answers1

1

edit categorie method to:

function categorie(){
    return $this->hasMany('App\Models\categorie','CategoryID');
}
  • Thanks. And is there any way I can define columns names in model. So that It automatically act accordingely. – Usman Khan Jul 14 '22 at 09:48
  • I know that but I want to know if this is possible or not... If we create app from scratch then we will build database according to laravel rules. but if DB already exists and not allowed to change its structure than we need that... – Usman Khan Jul 14 '22 at 14:51
  • Yes.it is impossible.in model you can use below codes to customiza all fileds and table name `protected $table = 'my_custom_table_name'; protected $primaryKey = "custom_tables_primary_column"; public $incrementing = false;` – Firooz Meysami Jul 14 '22 at 15:38