gpt4 book ai didi

php - 从不同的关系中获取最新的 eloquent laravel

转载 作者:行者123 更新时间:2023-12-01 09:44:36 26 4
gpt4 key购买 nike

我有3张 table

型号网址

class Url extends Model
{
public function users(){
return $this->belongsToMany(User::class);
}
public function url_status(){
return $this->hasMany(UrlStatus::class);
}
}

模型 UrlStatus
class UrlStatus extends Model
{
public function url()
{
return $this->belongsTo(Url::class);
}
}

模特用户
class User extends Authenticatable
{
use Notifiable, SoftDeletes, HasRoles;
public function urls(){
return $this->belongsToMany(Url::class);
}
}

在我的 Controller 中,我正在查询:
$url = Url::with('url_status','users')->where('list_status', true)->get();

如何获取最新的 url_status?

编辑 - -

这是我对迁移文件中每个表的结构

对于 URL 表
 Schema::create('urls', function (Blueprint $table) {
$table->increments('id');
$table->string('url');
$table->string('description');
$table->boolean('list_status');
$table->timestamps();
});

网址状态
Schema::create('url_status', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('url_id');
$table->integer('status_code');
$table->string('status');
$table->boolean('sms');
$table->boolean('email');
$table->timestamps();
});

用户表
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('contacts');
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->softDeletes();
});

最佳答案

你也可以这样试试

模型网址

public function latestUrlStatus(){
return $this->hasOne(UrlStatus::class)->latest();
}

像这样取
$urls = Url::with('latestUrlStatus','users')->where('list_status', true)->get();
foreach($urls as $url){
echo $url->latestUrlStatus->status_code;
}

关于php - 从不同的关系中获取最新的 eloquent laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52207683/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com