【问题标题】:Search query through foreign key通过外键搜索查询
【发布时间】:2018-06-19 19:42:29
【问题描述】:

我正在尝试通过我的 cmets 搜索连接到 user_id 外键的用户名

表: 评论 - id、评论、user_id、时间戳 用户 - id、姓名、用户名

型号:

class Comment extends Model
{

    public function author()
    {
        return $this->belongsTo('App\User','user_id');
    }
}

控制器:

public function index(Request $request)
{
     $comments = Comment::query()->orderby('created_at', 'DESC');

    $id=$request->]


    return view('comments.index')->withComment($comment);
}

查看:

            <div class="panel-body">
                {!! Form::open(['route' => 'comments.index', 'method' => 'GET']) !!}
                <div class="col-md-5">
                    {!! Form::label('id', 'Search By ID:') !!}
                    {!! Form::text('id', null, array('class' => 'form-control')) !!}
                </div>
                <div class="col-md-5">
                    {!! Form::label('username', 'Search By Username:') !!}
                    {!! Form::text('username', null, array('class' => 'form-control')) !!}
                </div>
                <div class="col-md-2">
                    {!! Form::submit('Find Comments', array('class' => 'btn btn-send ')) !!}
                </div>
                {!!Form::close()!!}

            </div>
@foreach($comment as $comments)
//data
@endforeach

【问题讨论】:

  • 为什么一个是 $cmets->where(col,val) 而另一个是 $cmets->where(col, operator, val) ?这行得通吗?
  • 唯一不起作用的是这行代码: $cmets->where($cmets->author->username, 'LIKE', $request->input('username') ) ->get()
  • 是 ->get() 填充 $cmets,还是因为没有 $collection = $... ->get();而回到遗忘状态;
  • 问题在于通过关系获取用户名而不是获取
  • @Watercayman 的代码更像我以前看到的那样〜然后只需确保您的用户表有一个用户名列或您的用户模型有 getUsernameAttribute()

标签: laravel laravel-5 laravel-5.4


【解决方案1】:

我认为它在构建器级别失败,因为您试图查询一个未知的对象。 IE 作者 LIKE 必须是子查询的一部分:

$comments = Comment::whereHas('author', function ($query) use($request) {
    $query->where(users.username, 'LIKE', $request->input('username') )
}])->orderby('created_at', 'DESC')->get();

我知道您将不得不再次编写查询,但我认为这对您来说可能会成功。

【讨论】:

  • 得到一个错误,说用户名在评论表中不存在,这是真的。即使我使用'author.username'
  • 对不起 - 关系是关于用户的,对吧?尝试使用 users.username - 我编辑以反映。
  • 关系名称是作者,将用户与评论相关联
  • 是的,但关系是用户表,我假设它有一个用户名列。上面的编辑工作了吗?
  • 抱歉,没错。不管怎样,不幸的是它仍然会抛出错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-13
  • 2019-06-18
  • 1970-01-01
  • 2012-09-26
  • 1970-01-01
相关资源
最近更新 更多