Laravel从外键获取数据

时间:2018-10-26 04:04:20

标签: php laravel eloquent foreign-keys

我有两个表,一个叫做Submission,一个叫AssignSubmission

Submission属于AssignSubmission

public function assignsubmission()
{
    return $this->belongsTo('App\AssignSubmission');
}

AssignSubmission有很多Submission

public function submissions()
{
    return $this->hasMany('App\Submission');
}

它们与外键链接 在AssignSubmission中有iduser_idsubmission_id的外键是submitt_id。 在“提交”表中,它具有iduser_idfileurl

AssignSubmission submission_id中的

链接到-> Submission id。 我已将不同的提交分配给2个用户。 enter image description here

如何从外键获取数据? 我想在视图中显示网址或文件

enter image description here

5 个答案:

答案 0 :(得分:2)

我认为您的关系可能会倒退?

提交:

public function assignSubmissions()
{
    return $this->hasMany(AssignSubmission::class);
}

分配提交:

public function submission()
{
    return $this->belongsTo(Submission::class);
}

答案 1 :(得分:1)

如果您使用的是laravel关系。然后,您可以执行以下操作:(假设您的提交表模型名为Submission

App\Submission::with('assignsubmission')->get();

答案 2 :(得分:0)

如果您已经有Submission个对象$submission,则

$submission->assignSubmission->url将为您提供URL。

它将转换为属性名称的camalCase。

答案 3 :(得分:0)

您写错了关系,应该是这样  提交:

public function assignSubmissions()
    {
        return $this->hasMany('App\Submission');

    }

分配提交:

public function submission()
     {
             return $this->belongsTo('App\AssignSubmission');
     }

要获得结果,我正在考虑使用Submission和AssignSubmissions作为您的模型,因此您可以像这样获取

$submission = App\Submission::find(1)->assignSubmissions; 
$assignSubmissions = App\AssignSubmissions::find(1)->submission;

检查此链接以获取更多参考信息https://laravel.com/docs/5.7/eloquent-relationships#one-to-many

答案 4 :(得分:0)

您应该尝试以下操作:

提交模型

public function assignsubmission()
{
    return $this->hasMany('App\AssignSubmission');
}

AssignSubmission 模型

public function submissions()
{
    return $this->belongsTo('App\Submission','submission_id');
}