Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xcode/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 基于父对象的laravel关联模型的发现_Php_Laravel_Laravel 4_Eloquent - Fatal编程技术网

Php 基于父对象的laravel关联模型的发现

Php 基于父对象的laravel关联模型的发现,php,laravel,laravel-4,eloquent,Php,Laravel,Laravel 4,Eloquent,我想搜索类似的,这是由一个给定的用户在一个给定的职位。 我有一个Post模型:Post class Post extends \Eloquent { protected $fillable = []; public function likes() { return $this->morphMany('Like', 'likeable'); } } 还有一个类似的模型: class Like extends \Eloquent {

我想搜索类似的,这是由一个给定的用户在一个给定的职位。 我有一个Post模型:Post

class Post extends \Eloquent
{


    protected $fillable = [];

    public function likes()
    {
        return $this->morphMany('Like', 'likeable');
    }


}
还有一个类似的模型:

class Like extends \Eloquent
{
    protected $fillable = [];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\MorphTo
     */
    public function likeable()
    {
        return $this->morphTo();
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function owner()
    {
        return $this->belongsTo('User', 'owner_id');
    }

}
和laravel中提供的默认用户模型

现在我查询了Post模型,找到了一个使用Post_id的Post

$post=Post::find(10);
和用户模型类似

$user=User::find(1);
现在我想找到这个用户在Post10上制作的类似的东西,laravel中是否有任何函数可用于此

我知道我可以像使用原始where函数一样直接查询

\Like::whereLikeableId('10')->whereLikeableType('Post')->whereUserId('1')->get();
但这看起来很难看,我想知道拉威尔的做法。

你只需要:

$like = $post->likes()->where('user_id', 1)->first();

谢谢你的回答,这很有效。有什么方法可以这样做吗:like::likable$post->where'user_id',1,我的意思是另一种方法,这样它就独立于父模型了。你可以使用whereHas,但我认为这不会让事情变得更简单。你为什么要那样?