Laravel表加入

时间:2019-07-07 09:58:55

标签: php mysql laravel

我有三个表:

notes: id, business_id, note

businesses: id, title, description

businessimages : id, business_id, image

我得到我的顾客注释:

$customer = Auth::guard('customer-api')->user();

$notes = Note::where('customer_id', $customer->id)->with('business:id')- 
>orderBy('id', 'desc')->get();

现在我想获取每个笔记的notes.id,businesss.id,businesss.title,businesss.description,businessimages.image,并将它们全部显示在一个json数组中

我该怎么办?

3 个答案:

答案 0 :(得分:1)

Note::where('customer_id',$customer->id)
  ->join('businesses', 'businesses.id', '=', 'notes.buisness_id')
  ->join('businessimages', 'businesses.id', '=', 'businessimages.buisness_id')
  ->select(notes.id, businesses.id, businesses.title, businesses.description,businessimages.image)
  ->get();

答案 1 :(得分:0)

您应该考虑使用API Resources

这是组织模型(或模型集合)的好方法。

App \ Note


use Illuminate\Database\Eloquent\Model;

class Note extends Model
{
    public function business()
    {
        return $this->belongsTo('App\Business');
    }
}

App \ Business


namespace App;

use Illuminate\Database\Eloquent\Model;

class Business extends Model
{
    public function note()
    {
        return $this->hasOne('App\Note');
    }

    public function businessImage()
    {
        return $this->hasOne('App\BusinessImage');
    }
}

App \ BusinessImage


namespace App;

use Illuminate\Database\Eloquent\Model;

class BusinessImage extends Model
{
    protected $table = 'businessimages';

    public function business()
    {
        return $this->belongsTo('App\Business');
    }
}

App \ Http \ Resources \ Note


namespace App\Http\Resources;

class Note
{
    public function toArray($request)
    {
        return [
            'noteId' => $this->resource->id,
            'businessId' => $this->resource->business->id,
            'businessTitle' => $this->resource->business->title,
            'businessDescription' => $this->resource->business->description,
            'businessImage' => $this->resource->business->businessImage->image
        ];
    }
}

控制器中的某处

use App\Http\Resources\Note as NoteResource;

    public function foo()
    {
        $customer = Auth::guard('customer-api')->user();
        $notes = Note::where('customer_id', $customer->id)->with(['business','business.businessImage'])->orderBy('id', 'desc')->get();
        return NoteResource::collection($notes);
    }

答案 2 :(得分:0)

笔记模型;

public function business() {
    return $this->hasOne('App\Business', 'business_id', 'id');
}

业务模式;

public function businessImage()
{
    return $this->hasOne('App\BusinessImage', 'business_id', 'id');
}

您的控制器;

$notes = Note::where('customer_id', $customer->id)->with('business.businessImage')->orderBy('id', 'desc')->get();