本文介绍了从不同的关系中获取最新的雄辩的laravel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3张桌子

模型网址

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);
    }
}

在我的控制器中,我正在查询:

In my controller I'm querying :

$url = Url::with('url_status','users')->where('list_status', true)->get();

如何获取最新的url_status?

How can I get the latest url_status?

编辑---

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

This is my structure for each table in migration file

用于网址表

 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;
}

这篇关于从不同的关系中获取最新的雄辩的laravel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 23:25