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

Time:06-10

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.

CodePudding user response:

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']);

CodePudding user response:

you can't pass parametrized relations in with or withCount so i'd suggest to define 3 relations

// Code_2 model

  public static $toCountRelations = [
    'x22',
    'x23',
    'x24'
  ];

  public function x22()
  {
    return $this->hasMany(Code_1::class, '34222X234X4422', 'Code');
  }

  public function x23()
  {
    return $this->hasMany(Code_1::class, '34222X234X4423', 'Code');
  }

  public function x24()
  {
    return $this->hasMany(Code_1::class, '34222X234X4424', 'Code');
  }

  /**
   * note that this function will return 0 if no of above relations is loaded
   *
   * @return int
   */
  public function getCodesCountAttribute()
  {
    $sum = 0;
    foreach (self::$toCountRelations as $relation)
      if ($this->relationLoaded($relation)) {
      // this syntax for $relation = 'x22' will get value of 
      // $this->x22_count
        $sum  = $this->{$relation . '_count'};
      }
    return $sum;
  }

  // controller
  $detailed = Code_2::withCount(Code_2::$toCountRelations)->get(['id', 'Code', 'Desc']);  

at this step you have collection of models with values of x22_count, x23_count, x24_count and computed property codes_count returning global count of loaded relations so if in future columns list will change you can simply change $toCountRelations array with required relations

  • Related