Php 拉维表联接
我有三张桌子:Php 拉维表联接,php,mysql,laravel,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('b
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获取notes.id、businesss.id、businesss.title、businesss.description、businessimages.image
,并在一个json数组中显示它们
我该怎么办?注意::where('customer\u id',$customer->id)
->join('business','business.id','=','notes.business\u id'))
->加入('businessimages','businesss.id','=','businessimages.businessness\u id'))
->选择(notes.id、businesss.id、businesss.title、businesss.description、businessimages.image)
->get();
< /代码> 你应该考虑使用< /p>
这是组织模型(或模型集合)的好方法
应用程序\说明
use Illuminate\Database\Eloquent\Model;
class Note extends Model
{
public function business()
{
return $this->belongsTo('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);
}
注释模型
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();
你有没有做过一些研究或写过一些文章,但没有成功?看起来你根本没有尝试过。所提及的注释表中没有客户id
列。可能存在重复的