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

如何在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条)

相关推荐 更多相似问题