繁体   English   中英

Laravel:通过“有多个”关系订购 model

[英]Laravel: Order a model by "Has One Of Many" relationship

我有一个客户 model 有很多联系人。 我使用 Laravel 8 中的“Has One Of Many”关系定义了一个关系以获取客户的最新联系:

楷模

class Customer extends Model
{
    use HasFactory;

    public function contacts() 
    {
        return $this->hasMany(Contact::class);
    }

    public function latestContact()
    {
        return $this->hasOne(Contact::class)->ofMany('contacted_at', 'max')->withDefault();
    }
}

class Contact extends Model
{
    use HasFactory;

    protected $casts = [
        'contacted_at' => 'datetime',
    ];

    public function customer()
    {
        return $this->belongsTo(Customer::class);
    }
}

迁移(接触模型)

class CreateContactsTable extends Migration
{
    public function up()
    {
        Schema::create('contacts', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->softDeletes();

            $table->foreignID('customer_id');
            $table->string('type');
            $table->dateTime('contacted_at');
        });
    }
}

在我看来,我想向所有客户展示并通过他们最近的联系人订购他们 但是,我不知道该怎么做。

我试图通过 join 方法来实现它,但显然每个客户都有不同的条目。

$query = Customer::select('customers.*', 'contacts.contacted_at as contacted_at')
    ->join('contacts', 'customers.id', '=', 'contacts.customer_id')
    ->orderby('contacts.contacted_at')
    ->with('latestContact')

知道 Laravel必须有一个很好的方法或助手来实现这一点。 有任何想法吗?

我认为最干净的方法是使用子查询连接:

$latestContacts = Contact::select('customer_id',DB::raw('max(contacted_at) as latest_contact'))->groupBy('customer_id');

$query = Customer::select('customers.*', 'latest_contacts.latest_contact')
         ->joinSub($latestContacts, 'latest_contacts', function ($join){
            $join->on([['customer.id', 'latest_contacts.customer_id']]);
        })
        ->orderBy('latest_contacts.latest_contact')
        ->get();

更多信息: https://laravel.com/docs/8.x/queries#subquery-joins

我怀疑您的迁移存在问题,外键约束的定义如下:

检查文档:https://laravel.com/docs/8.x/migrations#foreign-key-constraints

方法一:定义外键约束

public function up()
{        
    Schema::create('contacts', function (Blueprint $table) {
        $table->id();            
        $table->foreignId('consumer_id')->constrained();          
                    
        $table->string('type');
        $table->dateTime('contacted_at');
        $table->timestamps();
        $table->softDeletes();
    });    
}

方法二:定义外键约束

public function up()
{        
    Schema::create('contacts', function (Blueprint $table) {
        $table->id();                        
        $table->unsignedBigInteger('customer_id');                        
        $table->foreign('customer_id')->references('id')->on('customers');
                    
        $table->string('type');
        $table->dateTime('contacted_at');
        $table->timestamps();
        $table->softDeletes();
    });    
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM