dongzhi6146 2019-02-28 10:52 采纳率: 100%
浏览 1198
已采纳

如何在Laravel中使用模型连接两个数据库表?

如何从两个模型连接这两个表:

Student.php:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $table = 'students';

}

StudentDetails.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ProductDetails extends Model
{
    protected $table = 'student_details';
}

然后在一个控制器中使用这两个模型:

    use App\Student;
    use App\StudentDetails;    
            public function index()
            {
                return Product::latest()
                  ->join('StudentDetails','StudentDetails.product_id','Product.product_id')
                  ->get();

                //I dont know what the right approach is but i was thinking of 
                  doing something like this
            }

我搞不懂StudentDetails模型的用途是什么。通过以下方式我才让它运行起来:

return Student::latest()
                  ->join('student_details','student_details.student_id','student.student_id')
                  ->get(); 
  • 写回答

3条回答 默认 最新

  • drexlz0623 2019-02-28 11:06
    关注

    you don't even want to create StudentDetailsto get data using the code you have used.

    the model StudentDetailsis need only when you get the data using relationships. for that you have to mention the relation ship between both tables. assuming it has-many relationship.

    class Product extends Model
    {
       protected $table = 'students';
       public function studentDetails(){
        return $this->hasMany(StudentDetails::class);
      }
    }
    

    Now the relationship mentioned. Now you can fetch the data using the below query.

    $product = Product::has('studentDetails')->get();
    

    Note: this will return the collection, if you want to get the studentDetails's id, you have to do like this

    $product->studentDetails[0]->id
    

    or

    $product->studentDetails->first()->id
    

    Hope this clear.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码