如何使用laravel查询构建器正确构建查询?

时间:2019-08-06 08:41:03

标签: php laravel postgresql

我有两个模型:用户和消息。它们以一对多关系绑定在一起(一个用户可以发送许多消息)。表用户具有“电子邮件”列,表消息具有“ r_email”列(这是同一字段)。因此,我需要进行如下查询:“ SELECT * FROM Users,消息WHERE Users.email = Message.r_email。我该怎么做?

我尝试过这样的事情:

 $messages = App\Message::with('users')->where('users.email', '=', 'messages.r_email')->get();

但是它给了我错误。有什么问题吗?

以这种方式绑定模型:

class User extends Authenticatable
{
use Notifiable;

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'name', 'email', 'password',
];

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token',
];

/**
 * The attributes that should be cast to native types.
 *
 * @var array
 */
protected $casts = [
    'email_verified_at' => 'datetime',
];

public function messages()
{
    return $this->hasMany(Message::class);
}
}

以及消息模型的代码:

class Message extends Model
{
    protected $fillable = ['message', 'r_email'];
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

2 个答案:

答案 0 :(得分:0)

尝试

<a href="#">
    <div>
      <img src="http://placehold.it/350x300?text=1">
    </div>
</a>

答案 1 :(得分:0)

尝试一下

componentDidMount(){
 fetch("http://localhost:3001/api/form/data")
.then(res=>res.json())
.then(data=>{
if(data){
this.setState.({editorHtml : data});
}
}).catch(ex){
//handle error here
}

希望获得帮助。