标签: eloquent

Laravel 雄辩的随机查询

我有这种雄辩的查询,我需要从表中随机抽取行,并有限制,但它返回错误,当我使用限制时,它只提取一行,无论我将什么数字作为限制。当我不使用限制时,它会返回随机行数。不知道我错过了什么。这是代码。

$questions = $query->whereRaw('RAND()')->take($limit)->get();
Run Code Online (Sandbox Code Playgroud)

提前致谢!

laravel eloquent

0
推荐指数
1
解决办法
273
查看次数

Eloquent - 关系表上的位置

我有模型存储和控制:

class Store extends Model{
    protected $fillable = ['code', 'name', 'country_id', 'active'];

    public function controls(){
        return $this->hasMany('App\Control');
    }
}

class Control extends Model{
    protected $fillable = ['store_id', 'user_id', 'saved_at'];

    public function store(){
        return $this->belongsTo('App\Store');
    }

}
Run Code Online (Sandbox Code Playgroud)

现在我想获得 5 个商店,其中没有控件或控件是所有控件中最旧的(created_at)。

我怎样才能用雄辩的方式创造这个条件?我知道如何使用 Joins 实现它,但我希望它使用“漂亮的代码”。

像 :D

\App\Store::with('controls')->whereNotNull('controls.created_at')->orderBy('controls.created_at', 'desc')->take(5)->get();
Run Code Online (Sandbox Code Playgroud)

laravel eloquent laravel-5

0
推荐指数
1
解决办法
1917
查看次数

Laravel:如何在查询中计数

我有以下查询:

App\User::join('gift_sents', function($builder){
      $builder->on('gift_sents.receiver_id', '=', 'users.id');
      })
      ->select('users.*', 'COUNT(gift_sents.receiver_id as total_posts')
      ->groupBy('gift_sents.id')
      ->orderBy('total_posts', 'ASC')
      ->limit(3)->get();
Run Code Online (Sandbox Code Playgroud)

计数不工作,它应该工作!

出现以下错误:

Column not found: 1054 Unknown column 'COUNT(gift_sents.receiver_id' in 'field list' (SQL: select用户.*,计数(gift_sents .receiver_id astotal_postsfrom用户inner joingift_sents ongift_sents .receiver_id=用户.id group bygift_sents .id order bytotal_postsasc limit 3)

php mysql laravel eloquent laravel-5

0
推荐指数
1
解决办法
1771
查看次数

如何从 created_at 获取唯一的年份值?

我有一个名为 的集合$products,其中的每个实例都有一个字段created_at。后者显然('Y-m-d H:i:s')在数据库中有格式。现在,很容易获得带有 unique 的实例created_at。不过,我想检索唯一的年份值created_at一个单一的表达(我可以在我的观点写)。我正在寻找的是:

$products->unique( year value ('Y' ONLY) of 'created_at' )
Run Code Online (Sandbox Code Playgroud)

该表达式的值应该为这样的事情:['2012', '2013', '2016']

laravel eloquent laravel-5.2

0
推荐指数
1
解决办法
1691
查看次数

如何在laravel中获得具有角色的用户?

我有一个用户模型,它与角色模型具有“多对多”关系。用户模型:

class User extends Model
{
    ...
    public function roles()
    {
        return $this->belongsToMany(Config::get('entrust.role'), Config::get('entrust.role_user_table'), 'user_id', 'role_id');
    }
}
Run Code Online (Sandbox Code Playgroud)

我有一个用户控制器,它有一种以 JSON 格式获取用户数据的方法:

class UserController extends Controller {
    ...

    // GET /user/3
    public function show(User $user)
    {
        // $user is a single user
        // return single user's data without roles
        // I want to get user WITH roles
        return $user;
    }

    // GET /users
    public function index(User $user)
    {
        // returns list of users with roles.
        $user->with('roles')->get();
    }
}
Run Code Online (Sandbox Code Playgroud)

该方法show()以 …

laravel eloquent laravel-5.2

0
推荐指数
1
解决办法
2926
查看次数

Laravel 5 eloquent:选择特定的关系列

我有 2 个模型:作者和帖子

在我的 Post 模型中,我有一个作者函数(一对多(逆)):

public function author()
    {
        return $this->belongsTo('App\Author', 'author_id');
    }
Run Code Online (Sandbox Code Playgroud)

现在我想将以下信息导出到 Excel:

身份证 | 标题 | 作者姓名

这是我尝试过的:

$posts = Post::with(array(
        'author' => function ($query) {
            $query->select('name');
        }))->select('id', 'title')->get();
Run Code Online (Sandbox Code Playgroud)

我得到的是一个空的作者姓名列。

我怎么了?

eloquent laravel-5

0
推荐指数
2
解决办法
5951
查看次数

尝试使用特征挂钩模型“更新”事件

我试图提供一种方法来跟踪用户何时对我的应用程序中的注释部分的模型进行更改。例如,John 修改了 2 个字段,将创建一条注释,说明 John 已从title“我的标题 1”更改为“我的标题 2”,并content从“Lipsum”更改为“Lipsum2”。

这是我创建的一个特征:

<?php

namespace App\Traits;

use Illuminate\Database\Eloquent\Model;

trait TrackChanges
{
    public $changes;

    public static function bootChangesTrait()
    {
        static::updating(function($model)
        {
            $this->changes = [];

            foreach($model->getDirty() as $key => $value)
            {
                $original = $model->getOriginal($key);

                 $this->changes[$key] = [
                    'old' => $original,
                    'new' => $value,
                ];
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

我在我的模型上成功地使用了这个特性。但是,我不确定如何捕获更改的内容,或者它们是否正常工作。

在我的控制器中我有:

$site = Site::findOrFail($id);

// Catch and cast the is_active checkbox if it's been unselected
if ( ! $request->exists('is_active') )
{
    $request->request->add([ 'is_active' …
Run Code Online (Sandbox Code Playgroud)

model traits laravel eloquent

0
推荐指数
1
解决办法
2454
查看次数

Laravel 5.4 hasManyTrough '调用未定义的方法 Illuminate\Database\Query\Builder::hasManyTrough()'

我正在努力寻找,我哪里出错了。这很容易,我遵循了 Laravel 说明https://laravel.com/docs/5.4/eloquent-relationships#has-many-through,但显然我需要一个更熟悉这种代码的人,就像我尝试获取 $stagingsystem 一样-stagesubtype 我得到错误

BadMethodCallException 带有消息“调用未定义的方法 >Illuminate\Database\Query\Builder::hasManyTrough()”

有人可以帮忙吗?

分期系统

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateStagingSystemsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('staging_systems', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->unique();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('staging_systems');
    }
}
Run Code Online (Sandbox Code Playgroud)

艺名

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateStageNamesTable extends Migration
{
    /** …
Run Code Online (Sandbox Code Playgroud)

php laravel eloquent

0
推荐指数
1
解决办法
4674
查看次数

关系没有传递到通知?

我创建了一个通知,我正在将模型传递给:

class NewMessage extends Notification implements ShouldQueue
{
    use Queueable;

    protected $message;

    public function __construct(Message $message)
    {
        $this->message = $message;
    }

    public function via()
    {
        return ['database'];
    }

    public function toArray()
    {
        Log::info($this->message);

        return [
            'message_id' => $this->message->id,
        ];
    }
}
Run Code Online (Sandbox Code Playgroud)

这就是我调用通知的方式:

$message = Message::where('user_id', Auth::user()->id)
    ->where('message_id', $message_id)
    ->with('topic')
    ->get();

$user->notify(new NewMessage($message));
Run Code Online (Sandbox Code Playgroud)

问题是当通知打印日志 ( Log::info($this->message);) 时,topic关系没有显示出来。

但是,我发现如果我toArray()将 nofitication 类中的函数更改为这个,它打印出来的效果很好:

public function toArray()
{
    $this->message->topic;

    Log::info($this->message);

    return [
        'message_id' => $this->message->id,
    ];
}
Run Code Online (Sandbox Code Playgroud)

为什么?我该如何解决?

laravel eloquent laravel-5 laravel-5.3 laravel-eloquent

0
推荐指数
1
解决办法
961
查看次数

Laravel 设置属性不起作用

我需要 2 个函数添加和更新用户社交与序列化数组到字符串之前插入到数据库这里我的代码

    <?php
use Illuminate\Database\Eloquent\Model as Model;
class User extends Model{
    protected $table = 'user';
    protected $primaryKey = 'user_id';

    protected $fillable = [
        'name', 
        'email', 
        'socials',
    ];

    public function getSocialsAttribute($value){
       return unserialize($value);
    }

    public function setSocialsAttribute($value){
        settype($value, 'array');
        $this->attributes['socials'] = serialize($value);
    }

}
Run Code Online (Sandbox Code Playgroud)

在我的控制器中

$user_id = User::insert($request->post);
Run Code Online (Sandbox Code Playgroud)

帖子数组与

array(
   'name'=>'A',
   'email'=>'Test@gmail.com',
   'socials'=> array(
     'facebook' => 'facebook.com',
     'twitter' => 'twiter.com'
   )
)
Run Code Online (Sandbox Code Playgroud)

但是数据库不会序列化数据!

php laravel eloquent laravel-5.2 laravel-eloquent

0
推荐指数
1
解决办法
1万
查看次数