我对订单和产品有很多关系.
<?php
class Order extends Eloquent {
public function user()
{
return $this->belongsTo('User');
}
public function products()
{
return $this->belongsToMany('Product');
}
}
?>
<?php
class Product extends Eloquent {
public function orders()
{
return $this->belongsToMany('Order');
}
}
?>
Run Code Online (Sandbox Code Playgroud)
需要获取每个产品的订购次数.在mysql中,可以使用以下查询来完成此任务
SELECT products.id, products.description, count( products.id )
FROM products
INNER JOIN order_product ON products.id = order_product.product_id
INNER JOIN orders ON orders.id = order_product.order_id
GROUP BY product_id
LIMIT 0 , 30
Run Code Online (Sandbox Code Playgroud)
以上查询的结果如下: -
id description count(products.id)
1 Shoes 3
2 Bag 2
3 …Run Code Online (Sandbox Code Playgroud) 我是laravel的新手,并创建一个基本的应用程序来控制关系.我实现了一对一的关系,并希望从基表和相关表中获取特定的列.我有两个表,即users和identity_cards.Relationship定义如下
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
//protected $hidden = array('password', 'remember_token');
protected $fillable = array('first_name','last_name','email','created_at','updated_at');
public function identity_cards()
{
return $this->hasOne('IdentityCard');
}
}
class IdentityCard extends Eloquent {
protected $table = 'identity_cards';
protected $fillable = array('issuance_date','expiry_date','issuance_location','user_id');
public $timestamps = false;
public …Run Code Online (Sandbox Code Playgroud)