带有“ with”和“ where condition”的Laravel模型查询不起作用

时间:2019-11-14 16:45:01

标签: laravel eloquent

此获取书签的查询与条件无关,与user_topics无关

$bookmarkedposts = BookmarkedPost::where('leader_id',$user_id)->get();

但是当我向其他模型添加添加关系时,它不起作用

$bookmarkedposts = BookmarkedPost::where('leader_id',$user_id)->with('user_topics.first_media')->get();

这是Bookmarked.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class BookmarkedPost extends Model
{
   public function user_topics()
    {
        return $this->hasOne('App\UserTopic','id')->where('isdelete',0)->where('isactive',1);
    }
}

bookmarked_posts_table_sturucture user_topics_table_stucture

2 个答案:

答案 0 :(得分:1)

已添加书签的帖子模型:

class BookmarkedPost extends Model
{
   public function user_topic()
    {
        return $this->belongsTo('App\UserTopic','user_topic_id', 'id');
    }
}

UserTopic模型:

class UserTopic extends Model
{
   public function bookmarder_posts()
    {
        return $this->hasMany('App\BookmarkedPost','user_topic_id', 'id');
    }
}

现在可以在函数内部使用

$bookmarkedposts = BookmarkedPost::where('leader_id',$user_id)->with('user_topic')->get();

答案 1 :(得分:0)

尝试一下

 BookmarkedPost::where('leade_id', $user_id)->with('user_topics');