我如何加入 Eloquent: 关系?
Posted
技术标签:
【中文标题】我如何加入 Eloquent: 关系?【英文标题】:How can I join with Eloquent: Relationships? 【发布时间】:2017-07-27 06:38:52 【问题描述】:我的查询是这样的:
<?php
public function getListReviews()
$reviews = Review::where('user_id', auth()->user()->id)
->get();
return $reviews;
从查询中,可以通过id获取所有review数据
我想要获取用户照片、商店照片和产品照片
我想让它使用 Eloquent:Relationships
如何通过 Eloquent:Relationships 获得它?
我的评论模型是这样的:
<?php
namespace App;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
use Jenssegers\Mongodb\Eloquent\HybridRelations;
class Review extends Eloquent
use HybridRelations;
protected $connection = 'mongodb';
protected $fillable = ['user_id', 'user_name', 'product_id', 'product_name', 'store_id', 'store_name', 'invoice_number', 'rating', 'comments', 'created_at', 'updated_at'];
public function user()
return $this->belongsTo(User::class);
我的用户模型是这样的:
<?php
namespace App;
...
class User extends Authenticatable
...
protected $fillable = ['name', 'email', 'password', 'birth_date', 'mobile_number', 'photo'];
public function store()
return $this->hasOne(Store::class);
我的店铺模型是这样的:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Store extends Model
protected $fillable = ['user_id', 'name', 'address', 'phones', 'total_product', 'photo'];
public function products()
return $this->hasMany(Product::class);
我的产品型号是这样的:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
protected $fillable = ['store_id','category_id','name', 'photo','description'];
public function store()
return $this->belongsTo(Store::class);
【问题讨论】:
【参考方案1】:如果您想从评论模型中找出产品和商店,请在Review
模型中添加两个方法,如下所示。
编辑App\Review.php
//You already have key to to find store i.e. store_id
public function store()
return $this->belongsTo(Store::class);
//You already have key to to find product i.e. product_id
public function product()
return $this->belongsTo(Product::class);
然后执行如下查询
$reviews = Review::where('user_id', auth()->user()->id)
->with('store')
->with('product')
->with('user')
->get();
您可以通过以下方式访问它们,
以$review
遍历$reviews
对象
$review->store->photo;
$review->product->photo;
$review->user->photo;
【讨论】:
以上是关于我如何加入 Eloquent: 关系?的主要内容,如果未能解决你的问题,请参考以下文章