laravel 模型关联

发布时间:2018-09-13 16:23:01 阅读:1047次

model

<?php

  1 <?php                         
  2 namespace App\Models\Baidussp;
  3 use Illuminate\Database\Eloquent\Model;
  4 class Apps extends Model      
  5 {                             
  6     protected $connection = 'ssp_common';
  7     protected $table ='ssp_apps';
  8     protected $fillable = ['name'];
  9     const CREATED_AT = 'create_time';
 10     const UPDATED_AT = 'update_time';
 11     public function slots_list()                                                                                                                                 
 12     {                         
 13         return $this->hasMany('App\Models\Baidussp\Slots','app_id','id');
 14     }                         
 15 }

?>

<?php                                                                          
        $id = Request::input('id');                                         
        $name = Request::input('name');                                     
        $status = Request::input('status');                                 
        $flow_user_id = Request::input('flow_user_id');                     
        $pagesize = Request::input('pageSize') == "" ? 10 : Request::input('pageSize');
        $page = Request::input('current') == "" ? 1 : Request::input('current');
        $apps = Apps::select('*');                                          
                                                                            
        $id && $apps->where('id', $id);                                     
        $name && $apps->where([['name', 'like', '%' . $name . '%']]);       
        $flow_user_id && $apps->where('flow_user_id', $flow_user_id);       
        if (($status == 0 && $status != '') || $status > 0) {               
            $apps->where('status', $status);                                
        }                                                                   
        $count = $apps->where('status', '>', -1)->count();                  
                                                                            
        //$result = $apps->where('status', '>', -1)->orderBy('id', 'desc')->offset(($page - 1) * $pagesize)->limit($pagesize)->get()->load(['slots_list' => function  
($query) {
        //    return $query->get();                                         
        //}]);                                                              
                                                                            
        //$result = $apps->where('status', '>', -1)->orderBy('id', 'desc')->offset(($page - 1) * $pagesize)->limit($pagesize)->get()->load('slots_list');
                                                                            
        //$result = $apps->where('status', '>', -1)->orderBy('id', 'desc')->offset(($page - 1) * $pagesize)->limit($pagesize)->withCount('slots_list as slots_count'))
->get()->load('slots_list');
                                                                            
        $result = $apps->where('status', '>', -1)->orderBy('id', 'desc')->offset(($page - 1) * $pagesize)->limit($pagesize)->with(['slots_list' => function ($query)  
{
            $query->select(['id','name','app_id'])->where('status','>',-1);                                                                                          
        }])->select(['id', 'name'])->get();                                 
        dd($result->toArray());                
?>               

CREATE TABLE `userinfo` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) DEFAULT NULL,
  `gendar` varchar(10) DEFAULT NULL,
  `age` int(10) DEFAULT NULL,
  `address` varchar(50) DEFAULT NULL,
  `addtime` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

CREATE TABLE `userinfo_detail` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL DEFAULT '0',
  `introduce` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

CREATE TABLE `userinfo_hobby` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userid` int(11) NOT NULL DEFAULT '0',
  `hobby` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

[root@web_beta2 user.www.com]# find . -name "*.php" -mtime -1

./routes/web.php
./app/Models/Userinfo_detail.php
./app/Models/Userinfo_hobby.php
./app/Models/Userinfo.php
./app/Http/Controllers/UserinfoController.php

[root@web_beta2 user.www.com]#   

[root@web_beta2 user.www.com]# cat routes/web.php |grep userinfo
Route::match(['get', 'post'],'/userinfo', 'UserinfoController@index');

[root@web_beta2 user.www.com]# cat ./app/Models/Userinfo_detail.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Userinfo_detail extends Model
{
    protected $table = 'userinfo_detail';
    //取消 created_at 和 updated_at
    public $timestamps = false;
    //设置为时间戳
    protected $dateFormat = 'U';
    //字段改名 created_at 和 updated_at
    const CREATED_AT = 'creation_date';
    const UPDATED_AT = 'last_update';
    //设置不同的数据库链接
    //protected $connection = 'connection-name';

    /**
     * 获取与用户介绍
    */
    public function introduce()
    {
        return $this->belongsTo('App\Models\Userinfo');
    }
}

[root@web_beta2 user.www.com]# cat ./app/Models/Userinfo_hobby.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Userinfo_hobby extends Model
{
    protected $table = 'userinfo_hobby';
    //取消 created_at 和 updated_at
    public $timestamps = false;
    //设置为时间戳
    protected $dateFormat = 'U';
    //字段改名 created_at 和 updated_at
    const CREATED_AT = 'creation_date';
    const UPDATED_AT = 'last_update';
    //设置不同的数据库链接
    //protected $connection = 'connection-name';

    /**
     * 获取与用户介绍
    */
    public function hobby()
    {
        return $this->belongsTo('App\Models\Userinfo');
    }
}

[root@web_beta2 user.www.com]# cat ./app/Models/Userinfo.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Userinfo extends Model
{
    protected $table = 'userinfo';
    //取消 created_at 和 updated_at
    public $timestamps = false;
    //设置为时间戳
    protected $dateFormat = 'U';
    //字段改名 created_at 和 updated_at
    const CREATED_AT = 'creation_date';
    const UPDATED_AT = 'last_update';
    //设置不同的数据库链接
    //protected $connection = 'connection-name';
    /**
     * 获取与用户介绍
    */
    public function introduce()
    {
        return $this->hasOne('App\Models\Userinfo_detail','user_id');
    }
    /**
     * 获取与用户爱好
    */
    public function hobby()
    {
        return $this->hasMany('App\Models\Userinfo_hobby','userid');
    }
    //本地作用域
    public function scopeGendar($query,$type)
    {
        return $query->where('gendar', '=', $type);
    }
}

[root@web_beta2 user.www.com]# cat ./app/Http/Controllers/UserinfoController.php
<?php
//http://test.user.www.com/userinfo/?gendar=m
namespace App\Http\Controllers;
use App\Models;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
class UserinfoController extends Controller
{
    /**
     * 首页
     * @param Request $requset
    */
    public function index(Request $request){
        print_r($request->all());
        //$list = Models\Userinfo::where('id',2)->first();
        $list = Models\Userinfo::gendar('m')->first();
        echo "<pre>";
        //print_r($list->toArray());
        //exit;
        $list->introduce;
        //print_r($list->introduce);
        $list->hobby;
        $data = $list->toArray();
        //print_r($data);
        $list = Models\Userinfo::all();
        $list->load('introduce');
        $list->load('hobby');
        //print_r($list->toArray());
        $news = Models\Userinfo::where(function($query) use ($request) {
                    //人工编辑 & 推荐栏目 & 当天
                    $query->where('age', 34);
                    if($request->input('gendar')){
                        $gendar = $request->input('gendar');
                        $query->where('gendar', $gendar);
                    }
        })->get();
        print_r($news->toArray());
        $cacheKey = "userinfo_key";
        $pageSize = 1;
        $result = Cache::remember($cacheKey,1,function() use ($request,$pageSize){
                $news = Models\Userinfo::where(function($query) use ($request) {
                            //人工编辑 & 推荐栏目 & 当天
                            $query->where('age', 34);
                            if($request->input('gendar')){
                                $gendar = $request->input('gendar');
                                $query->where('gendar', $gendar);
                            }
                })->first()->toJson();
                return $news;
        });
        $value = Cache::get($cacheKey);
        $data = json_decode($value,true);
        print_r($data);
        $cacheKey = "userinfo_key_1";
        $pageSize = 1;
        $result = Cache::remember($cacheKey,1,function() use ($request,$pageSize){
                return "asdfasdfasdf";
        });
        $value = Cache::get($cacheKey);
        echo $value;
    }

如有问题,可以QQ搜索群1028468525加入群聊,欢迎一起研究技术

支付宝 微信

有疑问联系站长,请联系QQ:QQ咨询
下一篇:laravel 模块化

转载请注明:laravel 模型关联 出自老鄢博客 | 欢迎分享