Home > Mobile >  '?' in where condition Laravel
'?' in where condition Laravel

Time:12-05

I am try to get the relating to 'comment' model 'commentsRating' model.

 return $this->hasMany(commentRating::class,'comment_id','id')->toSql();

And get the following output:

 "select * from `comment_ratings` where `comment_ratings`.`comment_id` = ? and `comment_ratings`.`comment_id` is not null"

Comment model is:

class Comment extends Model
{
    use HasFactory;

    protected $fillable = [
        'body',
        'user_id',
        'item_id'
    ];

    protected $casts = [
        'user_id' => 'integer',
        'item_id' => 'integer',
    ];

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

    public function post()
    {
        return $this->belongsTo(Items::class, 'id');
    }

    public function ratings()
    {
        return $this->hasMany(commentRating::class,'comment_id','id')->toSql();
    }

}

And the rating model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class commentRating extends Model
{
    use HasFactory;

    protected $guarded = [];

    protected $fillable = [
        'comment_id',
        'user_id'
    ];

    public function user()
    {
        return $this->belongsTo('App\Models\User');
    }

    public function comment()
    {
        return $this->belongsTo('App\Models\Comment');
    }
}

CodePudding user response:

this is because laravel by default bind the variables to the query, you can use:

return $this->hasMany(commentRating::class,'comment_id','id')->dd();

this will return two values, the query with ?, and the array of values to bind

  • Related