Search code examples
phpmysqleloquentmodellaravel-9

How to dynamically set foreign key in a eloquent model laravel and how to use it with withCount


i have a column name in a table like below

Table Code 1

34222X234X4422 34222X234X4423 34222X234X4424
A1 A15 A15
A1 A6 A7
A3 A3 A3
A3 A3 A7
A5 A15 A8

Table Code 2

ID cid Code Desc
1 4422 A1 desc 1
2 4423 A2 desc 2
3 4422 A3 desc 3
4 4424 A4 desc 4

and so on

I want to count how many record from table Code 2 are exist in table Code 1 column 34222X234X4422, 34222X234X4423, 34222X234X4424 depend on Code_2.cid using Eloquent Laravel withCount.

I am thinking of using Model Relation one-to-many, but the foreign key cannot be static. Is it possible to passing parameter from controller to model relationship and how to input it in the withCount?

I am trying this:

class Code_2 extends Model
{
public function unit($id)
    {
        return $this->hasMany(Code_1::class, $id, 'code);
    }
}

here is my controller

$column = '34222X234X4424';
$detail1 = Code_2::withCount(['unit => function(Builder $query) use ($column){
            $query->on('code_1.'.$column, '=', 'code_2.code');
        },])->get(['id', 'code', 'decs']);

Turn out to be error "Too few arguments to function App\Models\Code_2::unit()".

How can i fix this?

Thank you.

Note: I cannot change the database at all. Just view it only.


Solution

  • You can create a variable in model and pass value for it same as :

    Model :

    class Code_2 extends Model
    {
    
        protected $table = 'code_2';
        protected $field;
        public function __construct($field = 'code_2_id')
        {
            $this->field = $field;
        }
    
        public function unit()
        {
            return $this->hasMany(Code_1::class, $this->field, 'Code');
        }
    }
    

    And Controller you can use :

    $column = '34222X234X4424';
    $model = new Code2($column);
    $detail1 = $model->withCount('unit')->get(['id', 'code', 'decs']);