首页 > 解决方案 > Laravel - belongsToMany 的关系和最后一个 belongsToMany 的关系

问题描述

我怎样才能获得我的 belongsToMany 关系中的最后一个条目?

我有模型报价和模型状态

class Offer extends Model
{
    /**
     * The statuses that the offer belongs to.
     */
    public function statuses()
    {
        return $this->belongsToMany('App\Models\Status')->withPivot('user_id');
    }

    /**
     * The current status for the offer.
     */
    public function currentStatus()
    {
        return $this->statuses->last();
    }
}

currentStatus()不起作用。

Call to undefined method App\Models\Status::addEagerConstraints()当我做的时候我得到Offer::first()->with('currentStatus');

我尝试了各种各样的东西:

public function currentStatus()
{
    return $this->belongsToMany('App\Models\Status')->withPivot('user_id')->latest();
}

public function latestMailLog()
{    
    return $this->hasOne('App\Models\MailLog')->latest('id');
}

等等

我什至不知道是否有可能做到这一点。但我做了类似的事情

public function mailLogs()
{
    return $this->hasMany('App\Models\MailLog');
}

public function latestMailLog()
{
    return $this->hasOne('App\Models\MailLog')->latest('id');
}

虽然这不是多对多的关系..

任何帮助将不胜感激:o)

标签: laravelrelationship

解决方案


idoffer_status数据透视表上添加一个自增主键列

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateOfferStatusTable extends Migration
{
    Schema::create('offer_status', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('user_id');
        $table->foreignId('offer_id')->constrained();
        $table->foreignId('status_id')->constrained();

        $table->index(['offer_id', 'status_id]);
    });
}

创建一个名为 OfferStatus 的 Pivot 模型。您可以使用工匠命令

php artisan make:model OfferStatus -p

OrderStatus.php 将在app/Models目录中创建

class OfferStatus extends Pivot
{
    public $incrementing = true;
}

现在在 Offer 模型类中调整状态和 currentStatus 的关系。

And define a scope to get the dynamic relation currentStatus working

/**class Offer extends Model
{
    /**
     * The statuses that the offer belongs to.
     */
    public function statuses()
    {
        return $this->belongsToMany('App\Models\Status')
            ->withPivot('user_id')
            ->using(OfferStatus::class);
    }

    /**
     * The current status for the offer.
     */
    public function currentStatus()
    {
        return $this->belongsTo(OfferStatus::class);
    }

    /**
     * Scope to make the dynamic relation currentStatus work
     */
    public function scopeWithCurrentStatus($query)
    {
        $query->addSelect(['current_status_id' => OfferStatus::select('id')
            ->whereColumn('offer_id', 'offers.id')
            ->latest()
            ->take(1)
        ])->with('currentStatus');
    }
}

Then you can access it as

$offers = Offer::withCurrentStatus()->get();

推荐阅读