如何在Laravel中为数据透视表编写关系?

时间:2018-04-23 07:11:10

标签: php laravel

这是我的表结构:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath 'com.google.gms:google-services:3.2.1'



        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

现在我有一个// tickets +----+------------+----------------------+--------+---------+-------------------+ | id | subject | content | closed | user_id | unique_product_id | +----+------------+----------------------+--------+---------+-------------------+ | 1 | subject1 | question1 | 0 | 123 | 2 | +----+------------+----------------------+--------+---------+-------------------+ // unique_product +----+---------------+------------+ | id | serial_number | product_id | +----+---------------+------------+ | 1 | 2342rd34fc | 3 | | 2 | fg34gt4r5t | 1 | | 3 | 34ffvv4et6 | 3 | +----+---------------+------------+ // products +----+--------------+ | id | name | +----+--------------+ | 1 | Router-rb51 | | 2 | Switch-sfx2 | | 3 | Router-rb300 | +----+--------------+ 这样的集合:

tickets

我可以在$tickets = tickets::where(user_id, "$user_id")->get(); foreach( $tickets as $ticket ){ $ticket->{I need to get the name of product here} } 模型中编写一个关系:

tickets

我需要一个与public function unique_product() { return $this->hasOne(unique_product::class, 'id', 'unique_product_id'); } 表的关系来获取产品名称(即products)。我应该怎么写这种关系?

1 个答案:

答案 0 :(得分:0)

$tickets = tickets::where(user_id, "$user_id")->with('unique_product.product')->get();

您可以使用with()优先加载。

但是对于使用with('unique_product.product')您必须定义unique_products和products之间的关系。

在UniqueProduct模型中创建新关系

public function product()
{
    return $this->BelongsTo(Product::class, 'id', 'product_id');
}

之后,您可以访问名称

的列
foreach( $tickets as $ticket ){
    $ticket->unique_product->product->name
}