laravel - 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)
解决方案
id
在offer_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();
推荐阅读
- xml - 将结构化 XML 国际邮寄地址格式化为文本
- c# - CSharpScript - TypeLoadException
- wordpress - 无法修复主页中的空间问题
- android - 如何在android中使用改造将参数和值传递给发布api?
- java - JOOQ 使用转换器将字符串转换为枚举
- javascript - 如何在 jQuery 中检测文本输入框中的变化
- python - 训练具有 2 个卷积操作的卷积网络,其共享权重必须保持范数为 1
- wso2is - WSO2IS 5.8 及更高版本是否有 CAS Authenticator 版本?
- postgresql - 试图将布尔列逻辑从 SQLITE 移动到 Postgres
- database - 表 'wp_users' 已存在