2017-03-07 52 views
2

我的查詢是這樣的:我如何能夠與雄辯:關係? (Laravel 5.3)

<?php 
public function getListReviews() 
{ 
    $reviews = Review::where('user_id', auth()->user()->id) 
        ->get(); 
    return $reviews; 
} 

從查詢,也可以通過ID得到所有評審數據

我想獲得用戶的照片,將照片及產品照片

我想得到它使用雄辯:關係

我怎樣才能得到它與雄辯:關係?

我的審查模式是這樣的:

<?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); 
    } 
} 

回答

3

如果您想從查看模型中找到產品和商店,請在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對象執行查詢,如下

$reviews = Review::where('user_id', auth()->user()->id) 
      ->with('store') 
      ->with('product') 
      ->with('user') 
      ->get(); 

,您可以如下訪問它們,

迭代作爲$review

$review->store->photo; 
$review->product->photo; 
$review->user->photo; 

希望它可以幫助你!

+0

太好了。有用。謝謝 –