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 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误