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

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.

I don't fully understand your case, but such simple joins can be easily and cleanly achieved by relations (checkout the docs)

As far as I understand you are trying to get, the products -students- along with their product details -student_details-.. if this is right, then you can just have


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

    public function details()
    {
        return $this->hasMany(ProductDetails::class); // or just use your kind of relation
    }
}

and then


public function index()
{
    return Product::with('details')
      ->latest()
      ->get(); // this is exactly equal to your join
}

if you dont want to make relation on model then you can do like:

   return Student::join('student_details','student_details.student_id','student.student_id')
-> select(stydent.*,student_details.*)->get();