我有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();
        });

URL 状态
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/

10-11 12:47