[英]Laravel - Relationship for belongsToMany and relationship for last belongsToMany
我怎样才能获得我的 belongsToMany 关系中的最后一个条目?
我有一个 model 报价和一个 model 状态
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)
在offer_status
pivot 表上添加一个自增主键列id
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 model。 您可以使用工匠命令
php artisan make:model OfferStatus -p
OrderStatus.php 将在app/Models
目录中创建
class OfferStatus extends Pivot
{
public $incrementing = true;
}
现在在 Offer model class 中调整状态和 currentStatus 的关系。
并定义一个 scope 以获得动态关系 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');
}
}
然后你可以访问它
$offers = Offer::withCurrentStatus()->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.