繁体   English   中英

如何将其他表中的一列与 Laravel 连接起来?

[英]How can I join one column in other table with Laravel?

实际上我使用的是 Laravel API。我有两个表,一个名为所有者,另一个是包含名为 unit_no 的属性的单位。 我想在带有 reactJs 的下拉列表中显示属性 unit_no 中的值。但我不知道如何在后端部分执行此操作。 这是我的 controller 代码:


   function addOwner(Request $request){
        $owner= new Owner();
        $owner->name=$request->input('name');
        $owner->email=$request->input('email');
        $owner->password=$request->input('password');
        $owner->telephone=$request->input('telephone');
        $owner->cin=$request->input('cin');
        $owner->presentAdress=$request->input('presentAdress');
        $owner->permenantAdress=$request->input('permenantAdress');
        $owner->file_path= $request->file('file')->store('owners');  
        $owner->save();
        return $owner;
    }

这是我的数据库:

   public function up()
    {
        Schema::create('owners', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->string('password');
            $table->string('telephone');
            $table->string('cin');
            $table->string('presentAdress');
            $table->string('permenantAdress');
            $table->string('file_path');
            $table->timestamps();
        });
    }

那么,您需要使用 eloquent。首先,如果您想进行联接,则需要在 2 个表中的一个表中添加一个公共属性。 例如,在 Units 中添加 owner_id 属性。 在 Unit & Owner model 中,您将定义 Owner 和 Unit 表之间的关系。

但是对于两个表的连接,一旦您将公共列添加到从 controller 迁移的 2 个表之一,您应该这样做。

$join_table = DB::table('owner')
        ->join('units', 'owner.id', '=', 'units.owner_id');

从这一点开始,您甚至可以获得所需的色谱柱。

$column = $join_table->pluck('unit_no');

无论如何,您应该改进问题不明确且不完整的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM