I'm trying to get a polymorphic relationship working on laravel but every test I make returns either null or ax exception on laravel's pretended SQL query...
FYI: My laravel version is 5.8
running on a MySQLserver 5.7
(WAMP package)
According to what I read on laravel's docs, I think I must use morphTo()
in the polymorphic model's class and morphMany()
on it's children tables, so I coded like this:
App\Models\Company
public function accounts(){
return $this->morphMany(Accountable::class, 'accountable');
}
App\Models\Account\Accountable
public function company()
{
return $this->belongsTo(Company::class);
}
public function accountable()
{
return $this->morphTo();
}
Migrations:
companies
Schema::create($this->tableName, function (Blueprint $table) {
$table->bigIncrements('id');
...
})
bank_accounts migration
Schema::create('bank_accounts', function (Blueprint $table) {
$table->bigIncrements('id');
...
});
company_has_accounts migration
Schema::create('company_has_accounts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->morphs('accountable');
...
});
Errors:
The thing is: Whenever I try to debug BankAccount::find(1)->company
I keep getting:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'company_has_accounts.company_type' in 'where clause' (SQL: select * from `company_has_accounts` where `company_has_accounts`.`c
ompany_id` = 1 and `company_has_accounts`.`company_id` is not null and `company_has_accounts`.`company_type` = Financeiro/Models/Account/BankAccount and `company_has_accounts`.`deleted_at` is null)
and when I try: Company::find(1)->accounts
I keep getting an empty Collection.
My objectives are:
App\Models\Account\BankAccount
public function company()
To return a App\Models\Company Object.
App\Models\Account\Company
public function accounts()
To return a collection of mixed "App\Models\Account\BankAccount" and "App\Models\Account\CreditCard" Objects, all belonging to the current App\Models\Account\Company Model, as filtered by the "company_id" column on "company_has_accounts" table.