Search code examples
laraveleloquentlaravel-8laravel-query-builder

The eloquent builder always attached orderby 'id' even after I have different PrimaryKey.How to get it solve?


I have my primaryKey as member_id (not id which is by default in a model) for my table Members. I have done the necessary changes in the model as follows.

class Member extends Model
{
use HasFactory;
public $timestamps = false;
/**
 * The primary key for the model.
 * 
 * @var string
 */
protected $primaryKey = 'member_id';

/**
 * The "type" of the auto-incrementing ID.
 * 
 * @var string
 */
protected $keyType = 'string';
public $incrementing = false;

but Member::query() always attach orderby id asc at the end of the query. So I get errors for unknown column id. I have tried to reorder from my query but in vain as it is always attached at the end of my query. How can i get the expected result?


Solution

  • After a long struggle with the code, I hunt down the main reason why it is not working as aspected.And thought to post the solution here so that someone like me do not waste time, in finding whats wrong. I had used Powergrid DataTable Package here and found this

    By default, PowerGrid uses the field id as your Model’s primary key.

    If your model uses a custom primary key, you must configure the property $primaryKey in your PowerGrid component.

    final class MemberList extends PowerGridComponent
    {
    use ActionButton;
    
    public string $primaryKey = 'members.member_id';
    
    public string $sortField = 'members.member_id';
    
     public function datasource(): Builder
    {
        
        return Member::query()
    }
    //..
    //..
    

    Now with this changes in the powergrid datatable file (where I fired the Member.query() function, it is working fine now.